LINQ - 用鲜明的价值? [英] LINQ - Distinct by value?
问题描述
可能重复:
鲜明()与拉姆达?
code:
news = (from New myNew in new News()
select myNew).Distinct().ToList();
不过这分明是物具有相同的价值观。我所需要的,在我的名单中, myNew
每个月。 (这样一个用于一月,一个用于februaru,等等)。比,新闻
将得到12的纪录。
but this Distinct is for "object" with same values. I need, into my list, a myNew
for each month. (so one for january, one for februaru, and so on). Than, news
will get 12 record.
是否有可能几分鲜明(myNew.Month)
?
推荐答案
您可以按月份和采取的第一个或最后一个或任何(你还没有告诉我们):
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());
修改:从上Habib的答案的评论我看到你想要12个月即使没有消息。然后,你需要做一个LINQ的外连接:
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...
}
修改:既然你有问题,实现在code中的查询,你不需要选择匿名类型,也包含了一个月。您也可以只选择了新闻本身:
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();
请注意,你现在得到12日消息,但他们中的一些可能是空
时,有没有消息在那个月。
Note that you now get 12 news but some of them might be null
when there are no news in that month.
这篇关于LINQ - 用鲜明的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!