开发者

How to compare column in 2 list with linq

How to compare and take only products in list product where p.street==a.street List products {p1, p2, p3} list address {a1, a2, a3}

Example:

  1. ListProduct= {P1, Paris} {P2, London} {P3 New York} {P4 Bagdad} {P5 Rome}
  2. Liste Adresse= {A1, Paris} {A2, Rome}

3.ListeProductResult= {P1, Paris} {P5 Rome}

Both solutions work very well Thanks I want to add a second list for comparison CategorieProduct={c1,c2}

It works but what is the best solution

 var result = from product i开发者_如何学Cn ListProduct 
         join address in ListAddresse on product.Street equals address.Street 
         join Categories in ListCategories on product.CategorieNom equals Categorie.CategorieNom  select product; 


The best way of doing this is to use a join - this will match the properties across the two different entities

var result = from product in ListProduct
             join address in ListAddresse on product.Street equals address.Street
             select product;

If this gives you multiple matches (e.g. if you had multiple matching addresses for a single product) then you could then additionally apply Distinct() to the output of this query.

For more examples of Linq in action, please see the excellent 101 linq examples on MSDN - including a section on joins - http://msdn.microsoft.com/en-us/vcsharp/ee908647#crossjoin


It can be done using those lists as follows: (assuming Street is the property that we are comparing)

var result = productsList
         .Where(product => addressList
                         .Any(address => address.Street == product.Street));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜