【问题标题】:Get all elements that only occur once获取只出现一次的所有元素
【发布时间】:2013-03-12 21:52:34
【问题描述】:

使用 LINQ,我可以得到只出现一次的所有 int 元素的列表吗?

例如

{1,2,4,8,6,3,4,8,8,2}

会变成

{1,6,3}

谢谢!

【问题讨论】:

    标签: c# linq list element distinct


    【解决方案1】:
    var result =
        from x in xs
        group xs by x into grp
        where grp.Count() == 1
        select grp.Key;
    

    喜欢吗?

    晚了 50 秒...:/

    【讨论】:

    • @lazyberezovsky +1 说实话:p
    【解决方案2】:
    list.GroupBy(i => i)
        .Where(g => g.Count() == 1)
        .Select(g => g.First());
    

    【讨论】:

      【解决方案3】:

      您可以使用的各种扩展方法:

      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());
      }
      

      And 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());
      }
      

      【讨论】:

        猜你喜欢
        • 2019-09-09
        • 2013-02-25
        • 1970-01-01
        • 2015-09-13
        • 1970-01-01
        • 2012-05-02
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        相关资源
        最近更新 更多