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

问题描述 投票:1回答:7

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

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

而且我按道具分组,我需要输出:

List<string>{ "a", "b", "c" }
c# linq c#-4.0 lambda
7个回答
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();

3
投票

更新

我单独使用Distinct()的原始答案是不够的。您需要按支持值分组,然后选择每个子集的第一个成员:

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

1
投票

如果你更喜欢:

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

0
投票

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


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

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

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();
© www.soinside.com 2019 - 2024. All rights reserved.