LINQ - different in meaning?

Possible duplicate:
Distinct () with lambda?

The code:

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

but this Distinct for the "object" with the same values. I need, on my list, myNewfor every month. (so one for January, one for februaru, etc.). Then newsget 12 entries.

Is it possible somehow Distinct(myNew.Month)?

+5
source share
5 answers

You can group by month and take the first or last or something else (you did not tell us):

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

Change . From the commentary on Habib’s answer, I see that you want 12 months, even if there is no news. Then you need to do "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...
}

. , , . :

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();  

, 12 , null, .

+12
var result  =  News()
  .GroupBy(p => p.Month)
  .Select(g => g.First())
  .ToList();
+5

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

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

Solution 2. Add IEqualityComparer and use this excellent () overload.

+4
source

Short manual solution

var vNews  =  News()   
              .GroupBy(p => p.Month, (key, p) => p.FirstOrDefault()) 
              .ToList();
+2
source
var vNews  =  News()   
              .GroupBy(p => p.Month)   
              .Select(g => g.First())   
              .ToList();
0
source

All Articles