我有以下数据:
Id | Value | OtherStuff
---------------------------
6 | 6 | 1
---------------------------
5 | 4 | 2
---------------------------
5 | 2 | 3
预期结果:
Id | Value | OtherStuff
---------------------------
6 | 6 | 1
---------------------------
5 | 4 | 2
那就是我需要每个ID的最大值。
我对如何执行此操作而不将其分为多个查询感到有些困惑,可以完成此操作吗?
更新:我认为我简化了这个问题:
var query = from st in StockStakes
join o in Organisations on j.OrganisationId equals o.OrganisationId into oGroup
from o in oGroup.DefaultIfEmpty()
where st.Stock.Status == "A"
select new
{
Id = st.Id,
Value = st.Value,
CustomerId = o.OrganisationId
};
上面的数据样本仍然存在...现在我如何构造查询以在每个ID旁边为我提供最大值?
最佳答案
var query = from x in data
group x by x.Id into x
select x.OrderByDescending(y => y.Value).FirstOrDefault()
基于更新的查询,该方法与第一个查询类似,但是由于您有多个表,因此需要将所有表分组为一个匿名对象,然后仅选择所需的列
var query = from st in StockStakes
join o in Organisations on j.OrganisationId equals o.OrganisationId into oGroup
from o in oGroup.DefaultIfEmpty()
where st.Stock.Status == "A"
group new { st, o } by st.Id into g
let largestValue = g.OrderByDescending(x => x.Value).FirstOrDefault()
select new
{
Id = g.Key,
Value = largestValue.st.Value,
CustomerId = largestValue.o.OrganisationId
};
关于c# - 不是简单的Max,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31386717/