List with distinct values inside only
本问题已经有最佳答案,请猛点这里访问。
我有具有属性的对象列表
1 2 3 4 5 6 7 8 9 | foreach (var x in mydata) { var model = new MyViewModel() { Id = x.Days.Id, Name = x.Days.Name }; models.Add(model); } |
我正在返回具有重复项的列表(模型),如何返回内部不同项的列表?
您可以使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // 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); } |
如果要按ID区分元素:
1 2 3 4 5 6 7 8 9 10 | 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); } |