Use linq distinct function?

This question already has an answer here:

  • LINQ's Distinct() on a particular property 17 answers

  • 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
         }); 
    

    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/

    链接地址: http://www.djcxy.com/p/51298.html

    上一篇: 如何从C#中的对象数组中获取不同的值?

    下一篇: 使用linq独特的功能?