When using GroupBy in linq, how can I get a list of group names?
If the original collection has objects with property prop:
prop = "a";
prop = "开发者_开发百科a";
prop = "b";
prop = "b";
prop = "c";
and I'm grouping by prop, I need the output:
List<string>{ "a", "b", "c" }
eg.
public class Foo
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
}
following code to group:
var foos = new List<Foo>();
var groupings = from foo in foos
group foo by foo.PropertyA
into groupedFoos
select groupedFoos;
/*
// the same as
var groupings = foos.GroupBy(foo => foo.PropertyA);
*/
var keys = from grouping in groupings
select grouping.Key;
.GroupBy()
will return IEnumerable<IGrouping<TKey, TSource>>
if you just want the distinct properties, you can still go for .Distinct()
, eg:
var keys = (from foo in foos
select foo.PropertyA).Distinct();
UPDATED
My original answer of using Disticnt() alone is insufficient. You need to GroupBy the prop value, and then select the first member of each subset:
myList.GroupBy(i => i.prop).Select(i => i.First()).ToList().ForEach(i => Console.Write(i.prop + ", "));
Demo code
Here's some code that illustrates the groupings.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var myList = new List<Foo>() {
new Foo(){ prop = "a", anotherProp = "z"},
new Foo(){ prop = "a", anotherProp = "x"},
new Foo(){ prop = "b", anotherProp = "x"},
new Foo(){ prop = "b", anotherProp = "y"},
new Foo(){ prop = "c", anotherProp = "z"}
};
// Display groups.
myList.GroupBy(i => i.prop).ToList().ForEach(j =>
{
Console.WriteLine("\t");
j.ToList().ForEach(k => Console.Write(k.prop + ", "));
});
Console.WriteLine();
Console.WriteLine(new string('-', 25));
// Display desired output.
myList.GroupBy(i => i.prop).Select(i => i.First()).ToList().ForEach(i => Console.Write(i.prop + ", "));
Console.WriteLine();
}
}
public class Foo
{
public string prop { get; set; }
public string anotherProp { get; set; }
}
}
If you prefer:
stuff.GroupBy(e => e.prop).Select(group => group.Key)
Using group by only gives individual items by your comparison function. if the comparison is done by prop
it will return the objects with distinct prop
only. all you need to do is iterate over them and select only prop
.
List<strings> groups context.YourObjects.Select(o => o.prop).Distinct().ToList();
var q = from a in yourList
group a by a.prop into b
select b.Key;
List<MyClass> source = getSource();
List<IGrouping<KeyType, MyClass>> groups = source
.GroupBy(x => x.prop)
.ToList();
List<KeyType> keys = groups
.Select(g => g.Key)
.ToList();
精彩评论