zoukankan      html  css  js  c++  java
  • 检索出 IList<T> 或 List<T>中的不重复数据 Distinct()

    Distinct()方法在MSDN中的示例

    public class Product
    {
        public string Name { get; set; }
        public int Code { get; set; }
    }
    Product[] products = { new Product { Name = "apple", Code = 9 }, 
                           new Product { Name = "orange", Code = 4 }, 
                           new Product { Name = "apple", Code = 10 }, 
                           new Product { Name = "lemon", Code = 9 } };
    var lstDistProduct = products.Distinct();
    foreach (Product p in list1)
    {
         Console.WriteLine(p.Code + " : " + p.Name);
    }

    但在实际使用中发现往往无法实现筛选出不重复的数据的目的

    查找相关资料获得如下方法:

    方法1:使用MoreLinq库

    var list1 = products.DistinctBy(x=> x.Code);
    
    
    
    
    foreach (Product p in list1)
    {
         Console.WriteLine(p.Code + " : " + p.Name);
    }

    方法2:

    class ProductComparare : IEqualityComparer<product>
        {
            private Func<Product, object> _funcDistinct;
            public ProductComparare(Func<Product, object> funcDistinct)
            {
                this._funcDistinct = funcDistinct;
            }
    
    
    
    
            public bool Equals(Product x, Product y)
            {
                return _funcDistinct(x).Equals(_funcDistinct(y));
            }
    
    
    
    
            public int GetHashCode(Product obj)
            {
                return this._funcDistinct(obj).GetHashCode();
            }
        }
    var list2 = products.Distinct(new ProductComparare( a => a.Code ));
    
    
    
    
                foreach (Product p in list2)
                {
                    Console.WriteLine(p.Code + " : " + p.Name);
                }

    方法3:

     List<Product> list = products
                       .GroupBy(a => a.Code )
                       .Select(g => g.First())
                       .ToList();
    
    
    
    
                foreach (Product p in list)
                {
                    Console.WriteLine(p.Code + " : " + p.Name);
                }

    本人通过第三种方法得到了想要的不重复数据。

    本文参考文章链接 :http://www.codeproject.com/Articles/535374/DistinctBy-in-Linq-Find-Distinct-object-by-Propert

  • 相关阅读:
    javascript 的继承
    js Cookie的操作
    不要再拖别人的控件1.输出几个小东西
    POJ2586Y2K Accounting Bug
    POJ3239Solution to the n Queens Puzzle
    POJ2109Power of Cryptography
    POJ1753Flip Game
    POJ2965The Pilots Brothers' refrigerator
    POJ1328Radar Installation
    POJ2255Tree Recovery
  • 原文地址:https://www.cnblogs.com/xmily/p/3074975.html
Copyright © 2011-2022 走看看