【问题标题】:LINQ using C# questionLINQ 使用 C# 问题
【发布时间】:2011-06-21 07:01:04
【问题描述】:

我有一个List<T>,其中包含一些用户定义的类数据。

我想查找 2 个数据字段组合的唯一实例。

例如,如果条目包含字段名称和年龄,我想要名称和年龄组合的唯一情况,例如Darren 32,应该只检索一次,即使它在列表中多次。

这可以用 LINQ 实现吗?

谢谢。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您只需提取这些数据字段并使其唯一:

    var result = list
      .Select(x => new { Age = a.Age, Name = x.Name})
      .Distinct();
    

    这将创建一个匿名类型的 IEnumerable,其中包含一个 Age 和 Name 属性。

    如果您需要找到唯一数据背后的项目,您需要GroupBy。这将为列表提供每个组后面的单个项目。

    var result = list
      .GroupBy(x => new { Age = a.Age, Name = x.Name});
    
    foreach (var uniqueItem in result )
    {
        var age = uniqueItem.Key.Age;
        var name = uniqueItem.Key.Name;
        foreach (var item in uniqueItem)
        {
           //item is a single item which is part of the group
        }
    }
    

    【讨论】:

    • 你好 - 看起来不错,但类型是匿名的,而不是动态的。干杯。
    【解决方案2】:
    myList.Select(l => new { l.Name, l.Age })
          .Distinct()
          .ToDictionary(x => x.Name, x => x.Age)
    

    【讨论】:

    • 非常感谢,但是我该如何存储这两个值,比如字典?我收到一条错误消息,说无法转换?再次感谢。
    • 使用 ToDictionary 方法,这个问题的更多信息,看第一个答案:stackoverflow.com/questions/627867/…
    • 对于相同的 Name 和不同的 Age,字典会抛出 ArgumentException
    • 是的,将其存储在字典中没有意义,我将由 Darren Young 决定;我个人会将其保留在列表中
    • 我喜欢.ToLookup(...)。它像Dictionary<K, IEnumerable<V>> 一样工作,并通过重复名称停止问题。
    【解决方案3】:

    您必须编写自己的equality comparer,并使用Linq 的Distinct 函数。

    【讨论】:

      【解决方案4】:

      看看Distinct扩展方法

      【讨论】:

        【解决方案5】:

        简单:

        var people = new List<Person>();
        
        // code to populate people
        
        var uniqueNameAges =
            (from p in people
             select new { p.Name, p.Age }).Distinct();
        

        然后到字典:

        var dictionary =
            uniqueNameAges
            .ToDictionary(x => x.Name, x => x.Age);
        

        或者查找(在这种情况下非常像Dictionary&lt;string, IEnumerable&lt;int&gt;&gt;):

        var lookup =
            uniqueNameAges
            .ToLookup(x => x.Name, x => x.Age);
        

        如果您有名为“John”且年龄不同的人,那么您可以像这样访问他们:

        IEnumerable<int> ages = lookup["John"];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-07
          • 2010-12-19
          • 1970-01-01
          • 2011-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多