Using LINQ, can I get a list of all int elements that only occur once?
For instance
{1,2,4,8,6,3,4,8,8,2}
would become
list.GroupBy(i => i)
.Where(g => g.Count() == 1)
.Select(g => g.First());
var result =
from x in xs
group xs by x into grp
where grp.Count() == 1
select grp.Key;
like that?
50seconds too late ... :/
Various Extension Methods you could use:
public static IEnumerable<T> WhereUnique<T>(this IEnumerable<T> items)
{
return items.GroupBy(x => x).Where(x => x.Count() ==1).Select(x => x.First());
}
possibly slightly more performant, depending on the distribution of your data:
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());
}
And WhereUniqueBy, which works similiar to 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());
}