Tono Nam
Tono Nam

Reputation: 36048

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

Upvotes: 1

Views: 339

Answers (3)

FlyingStreudel
FlyingStreudel

Reputation: 4464

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...

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126834

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;

Upvotes: 0

Tim
Tim

Reputation: 15237

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

Upvotes: 3

Related Questions