我有功能
private void TotalOutcome(List<Prenumerator> prenumerators, List<Publication> publications)
{
foreach (Publication publication in publications)
{
foreach (Prenumerator prenumerator in prenumerators)
{
if (prenumerator.PublicationCode == publication.Code)
{
publication.Earnings += prenumerator.Count * publication.MonthPrice;
}
}
}
}
如何将此转换为linq?我目前的做法不起作用,不做任何事情:
publications = (from publication in publications
from prenumerator in prenumerators
where prenumerator.PublicationCode == publication.Code
select publication);
{
publication.Earnings += prenumerator.Count * publication.MonthPrice;
}
);
答案 0 :(得分:2)
正如其他人所说,LINQ不是更新操作的正确工具。您仍然可以使用LINQ部分地执行此操作,即计算部分,然后使用普通foreach
循环作为更新部件,例如:
foreach (Publication publication in publications)
{
var total = prenumerators.Where(o => o.PublicationCode == publication.PublicationCode)
.Sum(o => o.Count * publication.MonthPrice);
publication.Earnings += total;
}
答案 1 :(得分:1)
您可以像这样转换第二个循环
private static void TotalOutcome(List<Prenumerator> prenumerators, List<Publication> publications)
{
foreach (Publication publication in publications)
{
foreach (Prenumerator prenumerator in prenumerators.Where(prenumerator => prenumerator.PublicationCode == publication.Code))
{
publication.Earnings += prenumerator.Count * publication.MonthPrice;
}
}
}
答案 2 :(得分:1)
只是为了迂腐并充分利用Linq(我认为这是Forest Gump的引用)。这是har07代码的“改进”;但是,根据您工作的编码标准,有些地方可能不喜欢Linq的这种无偿使用。
publications.ForEach(publication =>
{
publication.Earnings = prenumerators
.Where(o => o.PublicationCode == publication.PublicationCode)
.Sum(o => o.Count * publication.MonthPrice);
});
我们实际上在我们的商店有一条规则,你不允许使用。如果你要放入其中的代表长于一行,我们就会有一个规则。
答案 3 :(得分:0)
第一步,我们应用了一些关联法则:
var cnt = 0;
foreach (Prenumerator prenumerator in prenumerators)
{
if (prenumerator.PublicationCode == publication.Code)
{
cnt += prenumerator.Count;
}
}
publication.Earnings = cnt * publication.MonthPrice;
这使下一步更容易:
publication.Earnings = prenumerators
.Where(p=>p.PublicationCode == publication.Code)
.Aggregate(p=> p.Count)) * publication.MonthPrice;
没有特别好的方法可以摆脱外循环。