LINQ:不同的值 [英] LINQ: Distinct values

查看:38
本文介绍了LINQ:不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从XML中设置了以下项目:

I have the following item set from an XML:

id           category

5            1
5            3
5            4
5            3
5            3

我需要这些物品的明确清单:

I need a distinct list of these items:

5            1
5            3
5            4

如何在LINQ中区分类别和ID?

How can I distinct for Category AND Id too in LINQ?

推荐答案

您是否要通过多个字段来区分?如果是这样,只需使用匿名类型和Distinct运算符,就可以了:

Are you trying to be distinct by more than one field? If so, just use an anonymous type and the Distinct operator and it should be okay:

var query = doc.Elements("whatever")
               .Select(element => new {
                             id = (int) element.Attribute("id"),
                             category = (int) element.Attribute("cat") })
               .Distinct();

如果您试图获取一组不同的较大"类型的值,但只查看了不同方面的某些属性子集,则可能希望DistinctBy如在 DistinctBy.cs :

If you're trying to get a distinct set of values of a "larger" type, but only looking at some subset of properties for the distinctness aspect, you probably want DistinctBy as implemented in MoreLINQ in DistinctBy.cs:

 public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
     this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     IEqualityComparer<TKey> comparer)
 {
     HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
     foreach (TSource element in source)
     {
         if (knownKeys.Add(keySelector(element)))
         {
             yield return element;
         }
     }
 }

(如果将null作为比较器传递,它将使用默认的比较器作为键类型.)

(If you pass in null as the comparer, it will use the default comparer for the key type.)

这篇关于LINQ:不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆