class obj
{
int typeId; //10 types 0-9
string uniqueString; //this is unique
}
假设有一个包含100个obj元素的列表,但只有10个唯一的typeID。
有没有可能写一个LINQ查询返回objs列表中的10个唯一int?
发布于 2011-06-04 02:49:47
objList.Select(o=>o.typeId).Distinct()
发布于 2016-03-04 20:23:31
如果只想使用纯Linq,可以使用groupby:
List<obj> distinct =
objs.GroupBy(car => car.typeID).Select(g => g.First()).ToList();
如果你想在整个应用程序中使用一个方法,就像MoreLinq所做的那样:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (!seenKeys.Contains(keySelector(element)))
{
seenKeys.Add(keySelector(element));
yield return element;
}
}
}
使用此方法仅通过Id属性查找不同的值,您可以使用:
var query = objs.DistinctBy(p => p.TypeId);
您可以使用多个属性:
var query = objs.DistinctBy(p => new { p.TypeId, p.Name });
发布于 2011-06-04 02:50:01
当然,使用Enumerable.Distinct
。
给定一个obj
集合(例如foo
),您可以这样做:
var distinctTypeIDs = foo.Select(x => x.typeID).Distinct();
https://stackoverflow.com/questions/6231360
复制相似问题