C# 检索除一个datamember之外的不同列表
您有一个大列表,目标是检索下面的新列表 今天:C# 检索除一个datamember之外的不同列表,c#,linq,C#,Linq,您有一个大列表,目标是检索下面的新列表 今天: number color brand size tiresize ----------------------------------------- 1 blue d 5 6 2 blue d 5 6 3 red b 3 3 4 red b 3 3 etc....
number color brand size tiresize
-----------------------------------------
1 blue d 5 6
2 blue d 5 6
3 red b 3 3
4 red b 3 3
etc....
目标:
目标是检索一个有区别的列表,然后删除“编号”
这个示例很小,实际上列表中大约有26个数据成员
我在考虑distinct(),但它考虑了所有datamember,我不想考虑“number”列
当您检索新列表时,请求使用与distincted列表相同的类
public Car
{
public int number
public string color
public string brand
public string size
public string tiresize
}
谢谢大家! var cars=新列表
var cars = new List<Car>
{
new Car{number = 1, color="blue", brand="d", size = "5", tiresize = "6"},
new Car{number = 2, color="blue", brand="d", size = "5", tiresize = "6"},
new Car{number = 3, color="red", brand="b", size = "3", tiresize = "3"},
new Car{number = 4, color="red", brand="b", size = "3", tiresize = "3"},
};
var distinctCars = cars.GroupBy(x => new {x.color, x.brand, x.size, x.tiresize});
foreach (var car in distinctCars)
{
Console.WriteLine(car.Key.color + ": " + car.Key.brand + ": " + car.Key.size + ": " + car.Key.tiresize);
}
{
新车{number=1,color=“blue”,brand=“d”,size=“5”,tiresize=“6”},
新车{number=2,color=“blue”,brand=“d”,size=“5”,tiresize=“6”},
新车{number=3,color=“red”,brand=“b”,size=“3”,tiresize=“3”},
新车{number=4,color=“red”,brand=“b”,size=“3”,tiresize=“3”},
};
var distinctCars=cars.GroupBy(x=>new{x.color,x.brand,x.size,x.tiresize});
foreach(在distinctCars中的var car)
{
Console.WriteLine(car.Key.color+”:“+car.Key.brand+”:“+car.Key.size+”:“+car.Key.tiresize);
}
单向,使用匿名类型,该匿名类型具有内置的Equals
+GetHashCode
实现,该实现比较所有属性:
var distinctCars = cars
.Select(c => new {c.color, c.brand, c.size, c.tiresize})
.Distinct()
.Select(x => new Car {color = x.color, brand = x.brand, size = x.size, tiresize = x.tiresize})
.ToList(();
其他方法是
Car
中覆盖Equals
+GetHashCode
- 还可以选择实施
IEquatable
IEqualityComparer
,您可以在Distinct
GroupBy您要检索的字段,,,可以是@AndreaConte建议的GroupBy,也可以是MoreLinq(on nuget)DistinctBy
var distinctCars = cars
.Select(c => new {c.color, c.brand, c.size, c.tiresize})
.Distinct()
.Select(x => new Car {color = x.color, brand = x.brand, size = x.size, tiresize = x.tiresize})
.ToList(();