Is there a better option for GroupBy for a dictionary (or solution) for a statement?

Is there a way to write a ToDictionary statement below using SQL-ish Linq syntax?

public class KeyedType { public string Name { get; set; } public string Value { get; set; } } Dictionary<string,List<KeyedType>> groups = list.GroupBy((g) => g.Name) .ToDictionary(g => g.Key, g => g.ToList()); 
+6
source share
2 answers

Whenever you find yourself with Dictionary<TKey, List<TSomething>> , you can happily use Lookup<TKey, TSomething> . If that turns out to be the case, you can use ToLookup to do this.

However, neither ToLookup nor your code has a query expression syntax, unfortunately.

+4
source

Be that as it may, having made GroupBy , you have already made out. Try converting to a dictionary if you really need to. For instance. using group:

 var groups = list.GroupBy(g => g.Name); foreach (var group in groups) { var groupName = group.Key; var valueList = group.Select(obj => obj.Value); foreach (var value in valueList) { //... } } 
0
source

Source: https://habr.com/ru/post/901733/


All Articles