我有带有属性的对象列表 Id
和Name
.
foreach (var x in mydata)
{
var model = new MyViewModel()
{
Id = x.Days.Id,
Name = x.Days.Name
};
models.Add(model);
}
我返回的列表(模型)包含重复项目,如何返回其中不同项目的列表?
如果你想要用 id 区分的元素:
foreach (var x in mydata)
{
var model = new MyViewModel()
{
Id = x.Days.Id,
Name = x.Days.Name
};
if(!models.Contains(x=>x.Id==model.Id)
models.Add(model);
}
您可以使用 HashSet<T>
,如下所示:
// Ids that was used before
HashSet<int> Ids = new HashSet<int>();
foreach (var x in mydata) {
// Check for duplicates
if (Ids.Contains(x.Days.Id))
continue; // <- duplicate
else
Ids.Add(x.Days.Id);
// Your code
var model = new MyViewModel() {
Id = x.Days.Id,
Name = x.Days.Name
};
models.Add(model);
}