使用LINQ,我可以获得仅出现一次的所有int元素的列表吗?
例如
{1,2,4,8,6,3,4,8,8,2}
会变成
{1,6,3}
谢谢!
答案 0 :(得分:17)
var result =
from x in xs
group xs by x into grp
where grp.Count() == 1
select grp.Key;
是那样的?
50秒太晚了......:/
答案 1 :(得分:11)
list.GroupBy(i => i)
.Where(g => g.Count() == 1)
.Select(g => g.First());
答案 2 :(得分:0)
您可以使用的各种扩展方法:
public static IEnumerable<T> WhereUnique<T>(this IEnumerable<T> items)
{
return items.GroupBy(x => x).Where(x => x.Count() ==1).Select(x => x.First());
}
性能可能略高,具体取决于数据的分布:
public static IEnumerable<T> WhereUnique<T>(this IEnumerable<T> items)
{
return items.GroupBy(x => x).Where(x => !x.Skip(1).Any()).Select(x => x.First());
}
WhereUniqueBy,它与MoreLinqs DistinctBy()
类似:
public static IEnumerable<T> WhereUniqueBy<T, TSelector>(this IEnumerable<T> items, Func<T, TSelector> func)
{
return items.GroupBy(func).Where(x => x.Count() ==1).Select(x => x.First());
}