代码:
news = (from New myNew in new News()
select myNew).Distinct().ToList();
但是这个 Distinct 是针对具有相同值的“对象”。我需要在我的列表中为每个月添加一个 myNew
。 (所以一个用于 1 月,一个用于 februaru,依此类推)。然后,news
将获得 12 条记录。
是否有可能是一种Distinct(myNew.Month)
?
最佳答案
您可以按月分组并取第一个或最后一个或其他任何内容(您没有告诉我们):
var news = News()
.GroupBy(n => n.Month)
.Select(grp => grp.Last());
编辑:从对 Habib 回答的评论中我看到,即使没有消息,您也想要 12 个月。然后你需要做一个“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
。
关于c# - LINQ - 按值区分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10514039/