How do I group into memory lists?

I have a list of Foo . Foo has the properties of Bar and Lum . Some Foo have the same meaning for Bar . How can I use lambda / linq to group my Foo into Bar so that I can iterate through each Lum s group?

+4
source share
2 answers

Deeno

Enjoy:

 var foos = new List<Foo> { new Foo{Bar = 1,Lum = 1}, new Foo{Bar = 1,Lum = 2}, new Foo{Bar = 2,Lum = 3}, }; // Using language integrated queries: var q = from foo in foos group foo by foo.Bar into groupedFoos let lums = from fooGroup in groupedFoos select fooGroup.Lum select new { Bar = groupedFoos.Key, Lums = lums }; // Using lambdas var q = foos.GroupBy(x => x.Bar). Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)}); foreach (var group in q) { Console.WriteLine("Lums for Bar#" + group.Bar); foreach (var lum in group.Lums) { Console.WriteLine(lum); } } 

To learn more about LINQ, read 101 LINQ Samples.

+3
source
 var q = from x in list group x by x.Bar into g select g; foreach (var group in q) { Console.WriteLine("Group " + group.Key); foreach (var item in group) { Console.WriteLine(item.Bar); } } 
+4
source

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


All Articles