• linq 之 Distinct的使用


     1         public class Product
     2         {
     3             public string Name { get;set;}
     4             public int Code { get; set; }
     5         }
     6         class ProductComparet : IEqualityComparer<Product>
     7         {
     8             public bool Equals(Product x, Product y)
     9             {
    10                 if (object.ReferenceEquals(x,y))
    11                 {
    12                     return true;
    13                 }
    14                 if (object.ReferenceEquals(x,null)||object.ReferenceEquals(y,null))
    15                 {
    16                     return false;
    17                 }
    18                 return x.Code == y.Code && x.Name == y.Name;
    19             }
    20 
    21             public int GetHashCode(Product product)
    22             {
    23                 if (object.ReferenceEquals(product, null))
    24                 {
    25                     return 0;
    26                 }
    27                 int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
    28 
    29                 int hashProductCode = product.Code.GetHashCode();
    30                 return hashProductName ^ hashProductCode;
    31 
    32             }
    33         }
    View Code
            static void Main(string[] args)
            {
       
                Product[] products = { new Product { Name = "apple", Code = 9 }, 
                           new Product { Name = "orange", Code = 4 }, 
                           new Product { Name = "apple", Code = 9 }, 
                           new Product { Name = "lemon", Code = 12 } };
    
                IEnumerable<Product> noduplicates = products.Distinct(new ProductComparet());
                foreach (var item in noduplicates)
                {
                    Console.WriteLine(item.Name+" "+item.Code);
                }
            }
    
  • 相关阅读:
    软件工程师的悲哀
    关于ControlTemplate 2
    DataTemplate总结2(学习)
    ObjectiveC——类
    6 Popular Ideas That Fail
    Develop Cross Platform Mobile App
    DP 与 DO(学习)
    Titanium颜色总结
    Illustrator Tips
    Titanium API
  • 原文地址:https://www.cnblogs.com/yangpeng-jingjing/p/3831897.html
Copyright © 2020-2023  润新知