State today is as follows.

IEnumerable<Beep>
  as = list.Where(e => e.Name == "A").Select(e => e.Property),
  bs = list.Where(e => e.Name == "B").Select(e => e.Property);
Dictionary<String, IEnumerable<Beep>> 
  = new Dictionary<String, IEnumerable<Beep>>()
    { { "A", as }, { "B", bs } };

I wonder how it can be refactored to make the dictionarization directly from the LINQ expression in one statement.

有帮助吗?

解决方案

Because you are getting a IEnumerable<Beep> you don't really want ToDictionary(), instead this is kind of what ToLookup() does.

var result = list.ToLookup(x => x.Name, x => x.Property);

this will output a ILookup<string, Beep> which is equivalent to a Dictionary<String, IEnumerable<Beep>>

Important note! One cavate to doing it this way is the resulting ILookup can not be further modified to add more items later where having a Dictionary<string, IEnumerable<Beep>> would allow you to add more items after the initial creation. If you want a dictionary you would need to do

var result = list.GroupBy(x=>x.Name)
  .ToDictionary(x=> x.Key, x=>x.Select(y=> y.Property));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top