-1

I have list of objects with properties Id and Name.

 foreach (var x in mydata)
 {                
    var model = new MyViewModel()
    {
       Id = x.Days.Id,
       Name = x.Days.Name                                   
    };                                    
    models.Add(model);
 }

I'm returning list (models) which has duplicate items, how can I return list of distinct items inside?

Habib
  • 212,447
  • 27
  • 392
  • 421
user1765862
  • 12,589
  • 27
  • 102
  • 186

2 Answers2

1

If you want elements distinct by 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);
 }
Saverio Terracciano
  • 3,829
  • 1
  • 32
  • 41
1

You can use HashSet<T>, something like that:

// 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);
}
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199