返回具有匹配属性的对象列表的C#
返回具有匹配属性的对象列表的C#
这个问题上面已经有答案了:
我有以下对象:
class Car{ int price; string color; string size; } var list = new List(); 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,因为我已经对此进行了一段时间的摸索
admin 更改状态以发布 2023年5月20日
首先,您应该通过 按颜色和大小分组,然后选择其 Count
大于 1 的项目
var result = list .GroupBy(c => string.Join(c.color, c.size)) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList();
另外,您应该将 color
和 size
标记为 public
字段(或者使用属性,这是更好的选项)