-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
  • 219,104
  • 29
  • 407
  • 436
user1765862
  • 13,635
  • 28
  • 115
  • 220

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,885
  • 1
  • 30
  • 42
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
  • 180,369
  • 20
  • 160
  • 215