在linq中使用GroupBy时,如何获取组名列表?

时间:2011-06-23 22:04:38

标签: c# linq c#-4.0 lambda

如果原始集合具有属性prop的对象:

prop = "a";
prop = "a";
prop = "b";
prop = "b";
prop = "c";

我正在按道具进行分组,我需要输出:

List<string>{ "a", "b", "c" }

7 个答案:

答案 0 :(得分:3)

例如

public class Foo
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
}

以下代码分组:

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()将返回IEnumerable<IGrouping<TKey, TSource>>

如果你只想要不同的属性,你仍然可以去.Distinct(),例如:

var keys = (from foo in foos
            select foo.PropertyA).Distinct();

答案 1 :(得分:3)

已更新

我单独使用Disticnt()的原始答案是不够的。您需要GroupBy prop 值,然后选择每个子集的第一个成员:

myList.GroupBy(i => i.prop).Select(i => i.First()).ToList().ForEach(i => Console.Write(i.prop + ", "));

演示代码

以下是一些说明分组的代码。

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; }
    }
}

答案 2 :(得分:1)

如果您愿意:

stuff.GroupBy(e => e.prop).Select(group => group.Key)

答案 3 :(得分:0)

使用group by仅通过比较功能提供单个项目。如果比较由prop完成,则它将仅返回具有不同prop的对象。您需要做的只是迭代它们并仅选择prop

答案 4 :(得分:0)

List<strings> groups context.YourObjects.Select(o => o.prop).Distinct().ToList();

答案 5 :(得分:0)

var q = from a in yourList 
group a by a.prop into b
select b.Key;

答案 6 :(得分:0)

List<MyClass> source = getSource();

List<IGrouping<KeyType, MyClass>> groups = source
  .GroupBy(x => x.prop)
  .ToList();

List<KeyType> keys = groups
  .Select(g => g.Key)
  .ToList();