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

| 如果原始集合的对象具有属性prop:
prop = \"a\";
prop = \"a\";
prop = \"b\";
prop = \"b\";
prop = \"c\";
并且我正在按道具分组,我需要输出:
List<string>{ \"a\", \"b\", \"c\" }
    
已邀请:
        例如。
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();
    
        更新 我最初仅使用Disticnt()的答案是不够的。您需要对prop值进行GroupBy,然后选择每个子集的第一个成员:
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; }
    }
}
    
        若你宁可:
stuff.GroupBy(e => e.prop).Select(group => group.Key)
    
        使用分组依据只能通过比较功能给出单个项目。如果比较是由ѭ11完成的,它将仅返回带有不同distinct11的对象。您只需要遍历它们并仅选择select11ѭ。     
        
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();
    

要回复问题请先登录注册