Home Articles

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

Asked
Viewed 361 times
1

让我们说我有两个汽车列表

列表1:

  • "Ferrari",2005,"$350,000"

  • "BMW",2009,"$29,000"

  • "Audi",2011,"$33,000"

列表2:

  • "Infinity",2005,"$267,000"

  • "BMW",2009,"$45,000"

  • "Ferrari",2005,"$330,000"

  • "Toyota",2009,"$35,000"

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

  • "Ferrari",2005,"$330,000"

  • "BMW",2009,"$29,000"

因为那些是名字重复的汽车,价格最低

3 Answers

  • 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

    像这样的东西?我假设您有Intersect的CarComparer IEquality位 .

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

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

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

Related