Code :
news = (from New myNew in new News()
select myNew).Distinct().ToList();
but this Distinct is for \"object\" with same values.
var result = News()
.GroupBy(p => p.Month)
.Select(g => g.First())
.ToList();
var vNews = News()
.GroupBy(p => p.Month)
.Select(g => g.First())
.ToList();
Short hand solution
var vNews = News()
.GroupBy(p => p.Month, (key, p) => p.FirstOrDefault())
.ToList();
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.
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.