在将新对象添加到列表之前,如何检查对象中的多个属性以查看其是否存在于列表中?Contains()在这里不起作用,那么应该怎么做呢?
我这里是一个大列表模型,我想将一些数据移植到一个没有重复值,具有唯一值的新的较短列表模型中。
谢谢..
public class Fee {
public string Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Vin { get; set; }
public string Color { get; set; }
}
public class Foo {
public string Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
List<Fee> modelVehicles = new List<Fee>();
List<Foo> returnVehicles = new List<Foo>();
modelVehicles.Add(new Fee() { Year = "2001", Make = "Ford", Model = "Mustang", Vin = "111", Color = "Green" });
modelVehicles.Add(new Fee() { Year = "2001", Make = "Ford", Model = "Mustang", Vin = "222", Color = "Red" });
modelVehicles.Add(new Fee() { Year = "2001", Make = "Ford", Model = "Mustang", Vin = "333", Color = "Black" });
foreach(var v in modelVehicles)
{
if (returnVehicles.Contains(new Foo { Year = v.Year, Make = v.Make, Model = v.Model }) == false)
{
returnVehicles.Add(
new Foo {
Year = v.Year,
Make = v.Make,
Model = v.Model
}
);
}
}
您可以使用GroupBy
operator,因为实际上您的操作是分组的:
returnVehicles = modelVehicles.GroupBy(x => new { x.Year, x.Make, x.Model },
x => new Foo() {
Year = x.Year,
Make = x.Make,
Model = x.Model
},
(key, values) => values.First())
.ToList();
并且如果您实现Equals
并GetHashCode
用于Foo
:
public class Foo
{
public string Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public override bool Equals(object obj)
{
Foo other = obj as Foo;
if (other == null)
return false;
return string.Equals(Year, other.Year) &&
string.Equals(Make, other.Make) &&
string.Equals(Model, other.Model);
}
public override int GetHashCode()
{
int hash = 13;
hash = (hash * 7) + Year.GetHashCode();
hash = (hash * 7) + Make.GetHashCode();
hash = (hash * 7) + Model.GetHashCode();
return hash;
}
}
这可以简化:
returnVehicles = modelVehicles.GroupBy(x => new Foo() {
Year = x.Year,
Make = x.Make,
Model = x.Model
},
(key, values) => key)
.ToList();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句