-5

How can I use linq distinct operator here to remove remove duplicate courses.Cours.Name,

var coursesList = from courses in not_subsribe
  select new SelectListItem
  {
      Text = courses.Cours.Name,
      Value = courses.Cours.ID
      .ToString()
  };
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
Zahid Nisar
  • 47
  • 1
  • 1
  • 5

2 Answers2

0

You can use:

var coursesList = courses.DistinctBy(c => courses.Cours.Name)
                         .Select(crs => new SelectListItem
                                          {
                                              Text = crs.Cours.Name,
                                              Value = crs.Cours.ID.ToString()
                                          });

Sorry, I forgot to mention that DistinctBy method is available in a 3rd party library called MoreLINQ. This library is available for download using Nuget Package manager from here: http://www.nuget.org/packages/morelinq/

And you can find out more about MoreLINQ from here: https://code.google.com/p/morelinq/

Khurram Hassan
  • 1,494
  • 1
  • 13
  • 21
0

You could use GroupBy on an anonymous type with both properties to make them distinct:

var coursesList = 
     from c in not_subsribe
     group c by new { Id = c.Cours.ID, Name = c.Cours.Name } into g
     order by g.Key.Name
     select new SelectListItem
     {
         Text = g.Key.Name,
         Value = g.Key.Id
     };

That works because an anonymous type automatically overrides Equals+GetHashCode for you what is needed for GroupBy or Distinct. So now you could also use Distinct:

var coursesList = not_subsribe
.Select(c => new { Id = c.Cours.ID, Name = c.Cours.Name })
.Distinct()
.OrderBy(x => x.Name)
.Select(x => new SelectListItem
     {
         Text = g.Key.Name,
         Value = g.Key.Id
     }); 
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Or you could just `Select` the anonymous object and then call `Distinct`. – Rawling Mar 10 '14 at 08:07
  • @Rawling: good point, i've edited my answer. I've used `GroupBy` since OP used already query syntax and i don't like mixing query and method syntax. – Tim Schmelter Mar 10 '14 at 08:17