Deferred Execution - Dictionary Output
I have a Linq query that returns about half a million rows. However, since I did not call ToList (), execution is still pending. So far so good.
I need the output Dictionary<int, List<DateTime>>
from this query that will return about 100,000 entries (Column Integer Values) in the dictionary.
I've tried something like this ...
var myDictionary = new Dictionary<int, List<DateTime>>();
var myDictionaryOutput = MyQuery.Select(p => AddOrUpdateDictionary(myDictionary, p));
Where MyQuery is my linq query and AddOrUpdateDictionary is a custom function I wrote.
In this project every dictionary entry which is not what I want.
I only need the output of the dictionary.
Sample data looks like this:
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
(2 keys of 3 lines <=> 100,000 keys of 500,000 lines),
1234 -> List<DateTime>{2015-08-24, 2015-08-25, 2015-08-26}
and
2345 -> List<DateTime>{2015-08-23}
My thoughts are evaluating MyQuery.ToList () and passing it to my custom function would not be very efficient as then I would have to iterate over half a million rows using ForEach for example.
Am I wrong or is there a better way to achieve what I want?
source to share
It sounds like you want to make a group with null
s filtering and then converting to a 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());
source to share