延期执行 - 字典输出 [英] Deferred Execution - Dictionary output
问题描述
我有一个返回约50万行的Linq Query。但是,由于我没有调用ToList(),执行仍然延迟。
I have a Linq Query that returns about half a million rows. However, since I have not called ToList(), the execution is still deferred. So far so good.
我需要一个字典< int,List< DateTime>
这将在Dictionary中返回大约100,000个条目(Distinct integer column values)。
I need a Dictionary<int, List<DateTime>>
output from this query which would return about 100,000 entries (Distinct integer column values) in the Dictionary.
我尝试过这样的东西...
I tried something like this ...
var myDictionary = new Dictionary<int, List<DateTime>>();
var myDictionaryOutput = MyQuery.Select(p => AddOrUpdateDictionary(myDictionary, p));
MyQuery是我的LINQ查询,AddOrUpdateDictionary是我写的一个自定义函数。
Where MyQuery is my linq query and AddOrUpdateDictionary is a custom function I wrote.
这个项目将每个条目都设置为不需要我的字典。
This projects each entry to a Dictionary which is not what I want.
我只想输入字典。
样本数据如下所示...
The sample data looks as follows ...
1234 | 2015-08-24 | 2015-08-25 | null |
1234 | null | 2015-08-26 | null |
2345 | null | null | 2015-08-23 |
我希望输出是一个具有两个键的字典
I want the output to be a Dictionary with two keys
(来自500,000行的3行的2个键=> 100,000个键),
(2 Keys from 3 rows <=> 100,000 keys from 500,000 rows),
1234 -> List<DateTime>{2015-08-24, 2015-08-25, 2015-08-26}
and
2345 -> List<DateTime>{2015-08-23}
我的想法是评估MyQuery.ToList()和将它传递给我的自定义函数将不会非常有效,因为我将不得不使用ForEach循环五十万行。
My thoughts are evaluating MyQuery.ToList() and passing it to my Custom function will not be very efficient as I would then have to loop through half a million rows using ForEach for example.
我错了,还是有一个
推荐答案
看起来你想做的是一个组过滤 null
s,然后转换为字典:
It looks like what you want to do is a group by with filtering null
s, and subsequent conversion to dictionary:
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());
这篇关于延期执行 - 字典输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!