获取具有特定条件的两个列表的交叉

时间:2011-05-26 18:13:41

标签: c# linq

让我们说我有两个汽车清单

的List1:

  • "法拉利",2005年," $ 350,000"
  • " BMW",2009年," $ 29,000"
  • "奥迪" 2011," $ 33,000名"

列表2:

  • "无限",2005年," $ 267,000"
  • " BMW",2009年," $ 45,000个"
  • "法拉利",2005年," $ 330,000"
  • "丰田",2009年," $ 35,000"

我知道我可以使用Intersect方法获取重复汽车列表。但我还想保留价格较低的那个。例如,我想要一些将返回的方法:

  • "法拉利",2005年," $ 330,000"
  • " BMW",2009年," $ 29,000"

因为那些是重复名称且价格最低的汽车

3 个答案:

答案 0 :(得分:3)

完全未经测试,但这样的事情怎么样?

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

答案 1 :(得分:1)

这样的东西?我假设您有相交的CarComparer IEquality位。

var cheapCars = list1.Intersect(list2, new CarComparer()).
    OrderBy(c => c.Price).
        GroupBy(c => c.Name).
            Select(g => g.FirstOrDefault());

您可能需要修复语法...

答案 2 :(得分:0)

以下查询将匹配BrandYear属性上的汽车。如果您只关心Brand,则可以更改连接条件以满足此目的。

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;