延迟执行 - 字典输出

Deferred Execution - Dictionary output

我有一个 return 大约有一百万行的 Linq 查询。但是,由于我没有调用 ToList(),执行仍然被推迟。到目前为止一切顺利。

我需要此查询的 Dictionary<int, List<DateTime>> 输出,它将 return 字典中的大约 100,000 个条目(不同的整数列值)。

我试过这样的东西...

var myDictionary = new Dictionary<int, List<DateTime>>();

var myDictionaryOutput = MyQuery.Select(p => AddOrUpdateDictionary(myDictionary, p));

其中 MyQuery 是我的 linq 查询,AddOrUpdateDictionary 是我编写的自定义函数。

这不是我想要的字典中的每个条目。

我只想要字典输出。

示例数据如下所示...

1234 | 2015-08-24 | 2015-08-25 | null       |
1234 | null       | 2015-08-26 | null       |
2345 | null       | null       | 2015-08-23 |

我希望输出是一个有两个键的字典

(3 行中的 2 个键 <=> 500,000 行中的 100,000 个键),

1234 -> List<DateTime>{2015-08-24, 2015-08-25, 2015-08-26}
and 
2345 -> List<DateTime>{2015-08-23}

我的想法是评估 MyQuery.ToList() 并将其传递给我的自定义函数不会非常有效,因为我必须使用 ForEach 循环遍历 50 万行。

我错了还是有更好的方法来实现我所追求的目标?

看来您想做的是通过过滤 nulls 进行分组,然后转换为字典:

var dict = MyQuery
    .Select(row => new {row.Id, Dates = new[] {row.Date1, row.Date2, row.Date3}})
    .SelectMany(row => row.Dates.Select(d => new {row.Id, Date=d}))
    .GroupBy(row => row.Id)
    .ToDictionary(g => g.Key, g => g.Select(r => r.Date).ToList());