List with distinct values inside only
This question already has an answer here:
如果你想通过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);
}
链接地址: http://www.djcxy.com/p/51308.html
上一篇: 使用LINQ的不同值
下一篇: 仅在内部列出不同的值