【发布时间】:2011-06-23 22:04:38
【问题描述】:
如果原始集合中有带有属性prop的对象:
prop = "a";
prop = "a";
prop = "b";
prop = "b";
prop = "c";
我按道具分组,我需要输出:
List<string>{ "a", "b", "c" }
【问题讨论】:
如果原始集合中有带有属性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() 的原始答案是不够的。您需要 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; }
}
}
【讨论】:
Key 来检索想要的值,那将更加优雅!
如果您愿意:
stuff.GroupBy(e => e.prop).Select(group => group.Key)
【讨论】:
使用 group by 仅通过比较功能给出单个项目。如果比较是由prop 完成的,它将仅返回具有不同prop 的对象。您需要做的就是遍历它们并仅选择 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();
【讨论】: