Get the intersect of two list with specific criteria
Lets say I have two list of Cars
List1:
List2:
I know that I can get a list of duplicate cars by using the Intersect method. But I would like to also keep the one that has the smaller price. For example I want some method that will return:
because those are the cars that repeat with name and they have the smallest price
完全没有经过测试,但这样的事情呢?
var result = from c1 in List1
             join c2 in List2 on c1.Name equals c2.Name
             select new CarInfo()
             {
                 Name = c1.Name, // Doesn't really matter which you take
                 Year = c1.Price < c2.Price ? c1.Year : c2.Year,
                 Price = c1.Price < c2.Price ? c1.Price : c2.Price
             };
Something like this? I'm assuming you have the CarComparer IEquality bit for the Intersect.
var cheapCars = list1.Intersect(list2, new CarComparer()).
    OrderBy(c => c.Price).
        GroupBy(c => c.Name).
            Select(g => g.FirstOrDefault());
You might have to fix syntax...
 The following query will match cars on Brand and Year properties.  If you only care about the Brand , you can alter the join criteria to meet that purpose.  
var results = from car1 in list1
              join car2 in list2 
                on new { car1.Brand, car1.Year } 
                equals new { car2.Brand, car2.Year }
              select (car1.Price <= car2.Price) ? car1 : car2;
上一篇: 在LINQ中用2个属性分组
下一篇: 获取两个列表与特定条件的交集
