LINQ - Distinct by value?

后端 未结 5 901
醉话见心
醉话见心 2021-01-12 17:00

Code :

news = (from New myNew in new News()
       select myNew).Distinct().ToList();

but this Distinct is for \"object\" with same values.

相关标签:
5条回答
  • 2021-01-12 17:13
    var result  =  News()
      .GroupBy(p => p.Month)
      .Select(g => g.First())
      .ToList();
    
    0 讨论(0)
  • 2021-01-12 17:15
    var vNews  =  News()   
                  .GroupBy(p => p.Month)   
                  .Select(g => g.First())   
                  .ToList();
    
    0 讨论(0)
  • 2021-01-12 17:20

    Short hand solution

    var vNews  =  News()   
                  .GroupBy(p => p.Month, (key, p) => p.FirstOrDefault()) 
                  .ToList();
    
    0 讨论(0)
  • 2021-01-12 17:25

    You could group by month and take the first or last or whatever(you haven't told us):

    var news = News()
               .GroupBy(n => n.Month)
               .Select(grp => grp.Last());
    

    Edit: From the comment on Habib's answer i see that you want 12 months even if there are no news. Then you need to do a "Linq Outer-Join":

    var monthlyNews = from m in Enumerable.Range(1, 12) // left outer join every month
                      join n in News() on m equals n.Month into m_n
                      from n in m_n.DefaultIfEmpty()
                      group n by m into MonthGroups
                      select new {
                          Month = MonthGroups.Key, 
                          LastNews = MonthGroups.Last() 
                      };
    foreach (var m in monthlyNews)
    {
        int month = m.Month;
        var lastNewsInMonth = m.LastNews;
        if (lastNewsInMonth != null) ; // do something...
    }
    

    Edit: Since you have problems to implement the query in your code, you don't need to select the anonymous type which contains also the month. You can also select only the news itself:

    var monthlyNews = from m in Enumerable.Range(1, 12) // every motnh
                      join n in news on m equals n.Month into m_n
                      from n in m_n.DefaultIfEmpty()
                      group n by m into MonthGroups
                      select MonthGroups.Last();  
    

    Note that you now get 12 news but some of them might be null when there are no news in that month.

    0 讨论(0)
  • 2021-01-12 17:39

    Solution 1. Get MoreLinq (also available as NuGet package and use

      News().DistinctBy(n => n.Property)
    

    Solution 2. Implement an IEqualityComparer and use this Distinct() overload.

    0 讨论(0)
提交回复
热议问题