转自:http://blog.csdn.net/q107770540/article/details/6371087
如果你还不了解Intersect, 可参考这往篇文章:http://blog.csdn.net/q107770540/archive/2011/03/18/6258109.aspx
实际项目中,往往需求会复杂的多
比如有这样一个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(); } }