Get all elements that only occur once

前端 未结 3 1909
情话喂你
情话喂你 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 09:53
    list.GroupBy(i => i)
        .Where(g => g.Count() == 1)
        .Select(g => g.First());
    
    0 讨论(0)
  • 2021-01-23 10:04
    var result =
        from x in xs
        group xs by x into grp
        where grp.Count() == 1
        select grp.Key;
    

    like that?

    50seconds too late ... :/

    0 讨论(0)
  • 2021-01-23 10:13

    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());
    }
    
    0 讨论(0)
提交回复
热议问题