Code :
news = (from New myNew in new News()
select myNew).Distinct().ToList();
但这个 Distinct 适用于具有相同值的“对象”。我需要在我的列表中添加一个myNew
每个月。 (所以一个用于一月,一个用于二月,依此类推)。比,news
将获得12条记录。
是否有可能是一种Distinct(myNew.Month)
?
您可以按月分组并取第一个或最后一个或其他任何内容(您没有告诉我们):
var news = News()
.GroupBy(n => n.Month)
.Select(grp => grp.Last());
Edit:从哈比卜的回答的评论中我看到即使没有消息你也想要 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...
}
Edit:由于您在代码中实现查询时遇到问题,因此不需要选择还包含月份的匿名类型。您还可以仅选择新闻本身:
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
当那个月没有消息的时候。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)