1. 程式人生 > >LINQ Intersect 自定義規則

LINQ Intersect 自定義規則

    實際專案中,往往需求會複雜的多

   比如有這樣一個Product類:

public class Product
  {
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public double UnitPrice { get; set; }
  }

需求是隻要兩個Product的 Id和price相同 即認為二者相等,這個可以這樣實現:

void Main()
{
   
var

productList1 =new List<Product>()
    {
   
new Product() { ProductId = 1001, ProductName = "Apple22", UnitPrice = 50 },
       
new Product() { ProductId = 1002, ProductName = "Mango", UnitPrice = 20 },
       
new Product() { ProductId = 1003, ProductName = "Orange"
, UnitPrice = 30 }
    };
   
       
var productList2 =new List<Product>()
        {
       
new Product() { ProductId = 1001, ProductName = "Apple11", UnitPrice = 50 },
       
new Product() { ProductId = 1002, ProductName = "Mango", UnitPrice =
25 },
       
new Product() { ProductId = 1004, ProductName = "PineApple", UnitPrice = 30 }
        };

   
    Console.WriteLine(
"ProductList1 Details");
    Console.WriteLine(
"*******************************");
   
foreach (Product product in productList1)
    {
        Console.WriteLine(
string.Format("Product Id:{0}, Product Name:{1}, UnitPrice:{2}", product.ProductId, product.ProductName, product.UnitPrice));
    }

    Console.WriteLine(
"/nProductList2 Details");
    Console.WriteLine(
"*******************************");
   
foreach (Product product in productList2)
    {
        Console.WriteLine(
string.Format("Product Id:{0}, Product Name:{1}, UnitPrice:{2}", product.ProductId, product.ProductName, product.UnitPrice));
    }

   
var items =productList1.Intersect(productList2,new ProductRowComparer());

    Console.WriteLine(
"/nIntersect Details");
    Console.WriteLine(
"*******************************");

   
foreach (Product product in items)
    {
        Console.WriteLine(
string.Format("Product Id:{0}, Product Name:{1}, UnitPrice:{2}", product.ProductId, product.ProductName, product.UnitPrice));
    }

   
/*
    ProductList1 Details
    *******************************
    Product Id:1001, Product Name:Apple22, UnitPrice:50
    Product Id:1002, Product Name:Mango, UnitPrice:20
    Product Id:1003, Product Name:Orange, UnitPrice:30
    
    ProductList2 Details
    *******************************
    Product Id:1001, Product Name:Apple11, UnitPrice:50
    Product Id:1002, Product Name:Mango, UnitPrice:25
    Product Id:1004, Product Name:PineApple, UnitPrice:30
    
    Intersect Details
    *******************************
    Product Id:1001, Product Name:Apple22, UnitPrice:50

    */


}

public class ProductRowComparer : IEqualityComparer<Product>
 {  
 public bool Equals(Product t1, Product t2)  
 {  
 return (t1.ProductId == t2.ProductId && t1.UnitPrice== t2.UnitPrice);  
 }  
 public int GetHashCode(Product t)  
 {  
 return t.ToString().GetHashCode();  
 }  
}