Get all elements that only occur once

前端 未结 3 1944
情话喂你
情话喂你 2021-01-23 09:09

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



        
3条回答
  •  半阙折子戏
    2021-01-23 10:13

    Various Extension Methods you could use:

    public static IEnumerable WhereUnique(this IEnumerable 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 WhereUnique(this IEnumerable 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 WhereUniqueBy(this IEnumerable items, Func func)
    {
        return items.GroupBy(func).Where(x => x.Count() ==1).Select(x => x.First());
    }
    

提交回复
热议问题