linq 不同对象集合 交集 差集

[csharp] view plain copy
  1. class Product  
  2. {  
  3.     public int ID { get; set; }  
  4.     public string SubID { get; set; }  
  5.     public double Price { get; set; }  
  6. }  
  7. class SubProduct  
  8. {  
  9.     public string ID { get; set; }  
  10. }  
[csharp] view plain copy
  1. var pList1 = new List<Product>  
  2. {  
  3.     new Product {ID = 1, SubID = "AA", Price = 0.1 },  
  4.     new Product {ID = 2, SubID = "BB", Price = 0.2 },  
  5.     new Product {ID = 3, SubID = "BB", Price = 0.4 },  
  6.     new Product {ID = 4, SubID = "AA", Price = 0.7 },  
  7.     new Product {ID = 5, SubID = "CC", Price = 0.3 }  
  8. };  
  9.   
  10. var pList2 = new List<SubProduct>  
  11. {  
  12.     new SubProduct { ID="AA" },  
  13.     new SubProduct { ID="BB" }  
  14. };  


交集 三种实现 ,差集在前面加非运算即可

1、

[csharp] view plain copy
  1. var result = pList1.Where(x => !pList2.Select(y => y.ID).Contains(x.SubID)).ToList();  


2、

[csharp] view plain copy
  1. var ids = pList2.Select(x => x.ID).Distinct().ToList();  
  2. var result1 = pList1.GroupBy(x => x.SubID).Where(x => ids.Contains(x.Key)).SelectMany(x => x).ToList();  


3、

[csharp] view plain copy
    1. var ids = pList2.Select(x => x.ID).Distinct().ToList();  
    2. var result = pList1.AsParallel().GroupBy(x => x.SubID).Where(x => ids.Contains(x.Key)).SelectMany(x => x).ToList();   
posted @ 2018-04-26 16:39  Net-Spider  阅读(409)  评论(0)    收藏  举报