开发者

Get the intersect of two list with specific criteria

开发者 https://www.devze.com 2023-03-08 10:44 出处:网络
Lets say I have two list of Cars List1: \"Ferrari\",2005,\"$350,000\" \"BMW\",2009,\"$29,000\" \"Audi\",2011,\"$33,000\"

Lets say I have two list of Cars

List1:

  • "Ferrari",2005,"$350,000"
  • "BMW",2009,"$29,000"
  • "Audi",2011,"$33,000"

List2:

  • "Infinity",2005,"$267,000"
  • "BMW",2009,"$45,000"
  • "Ferrari",2005,"$330,000"
  • "Toyota",2009,"$35,000"

I know that I can ge开发者_JAVA百科t 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:

  • "Ferrari",2005,"$330,000"
  • "BMW",2009,"$29,000"

because those are the cars that repeat with name and they have the smallest price


Completely untested, but how about something like this?

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;
0

精彩评论

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