答案 0 :(得分:1)
var listInfoDetail = _infoDetailRepository.Query(p => p.group == "x").ToList();
InfoDetail
表中有group == "x"
个条目。因此listInfoDetail
有3个项目。你这样做了两次,所以你最终得到6.行为是预期的。
我想分组并对结果变量求和以给出我想要的结果
如果您不想对逻辑进行更改,您可以获取结果变量并执行类似的操作,然后按expenseN
和name
进行分组,然后对{ {1}}
cost
但这对LINQ的使用非常低效。您应该寻求改进以下内容:
var resultGrouped = result
.GroupBy(x => new { x.expenseN, x.name })
.Select(y => new Info()
{
name = y.Key.name,
age = y.FirstOrDefault().age,
expenseN = y.Key.expenseN,
cost = y.Sum(z => z.cost),
group = y.FirstOrDefault().group
}).ToList();
和p.name = "a"
p.name = "b"
。您可以使用ToList()
listInfoDetail
和info1
醇>
最终所有这些代码都可以使用一个链式LINQ语句进行存档,效率更高,更短。
答案 1 :(得分:1)
以下代码将有助于您简化现有代码并帮助您获得所需的结果。
var result = from p in InfoDetails
where p.groups == "x"
group p by new { p.expenseN } into g
from c in Info
orderby c.name, g.FirstOrDefault().expenseN
select new
{
name = c.name,
age = c.age,
expenseN = g.FirstOrDefault().expenseN,
cost = g.Sum(x=>x.cost),
groups = g.FirstOrDefault().groups
};
或
var result = InfoDetails.Where(x=>x.groups=="x").GroupBy(x=>x.expenseN).SelectMany(t1 => Info.Select(t2 => new {
name = t2.name,
age = t2.age,
expenseN = t1.FirstOrDefault().expenseN,
cost = t1.Sum(x=>x.cost),
groups = t1.FirstOrDefault().groups
})).OrderBy(x=>x.name).ThenBy(x=>x.expenseN);