【问题标题】:C# Return list of objects with matching attributes [duplicate]C#返回具有匹配属性的对象列表[重复]
【发布时间】:2020-10-14 20:31:50
【问题描述】:

我有以下对象:

class Car{
   int price;
   string color;
   string size;
}

var list = new List<Car>();
list.Add...//add 20 cars

//I now want to select from this list any cars whose color and size matches that of any other car

list.Select(car => String.Join(car.color, car.size)) 

我想从此列表中选择一组字符串(颜色 + 大小),这些字符串存在于列表中的不止一辆汽车中

不知道在哪里继续使用 linq,因为我一直在努力解决这个问题

【问题讨论】:

  • 您希望结果是符合条件的汽车实例列表,还是符合条件的汽车的颜色+尺寸字符串列表?
  • 您的问题并不完全清楚,但似乎您想要“颜色”和“大小”的组合,然后生成所有匹配的集合。见GroupBy();特别是,在正确的键上进行分组(不是下面非常差的答案中显示的示例),然后仅返回组中元素计数大于一的那些组。参见重复分组。

标签: c# linq


【解决方案1】:
var groupedCars = list.
    GroupBy(c => c.color + c.size, c => c).
    Where(g => g.Count() > 1);

【讨论】:

    【解决方案2】:

    你应该先group the listcolorsize,然后选择Count大于1的项目

    var result = list
        .GroupBy(c => string.Join(c.color, c.size))
        .Where(g => g.Count() > 1)
        .Select(g => g.Key)
        .ToList();
    

    另外,您应该将colorsize 标记为public 字段(或使用属性,这是更好的选择)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      相关资源
      最近更新 更多