使用LINQ从多列多​​行获取最大值?

时间:2013-04-12 03:07:43

标签: linq linqpad

我正在使用LINQPad来评估我的linq查询。我的查询是这样的:

from o in MyTableFirst
join p in MyTableSecond on o.TheName equals p.TheName
where p.TheName == "CBA-123" && !p.Removed && 
   (o.ReturnPeriod ==100 || o.ReturnPeriod ==10)
select new {
   HMax1 = o.MaxValue1,
   HMax2 = o.MaxValue2,
   HMax3 = o.MaxValue3
}


此查询可以返回0或某些行数。

在LINQPad中,它返回我这样的东西:

HMax1 HMax2 HMax3
21.1 22.5
24.6 11.5

现在,我将如何获得这些返回行的最大值&列?
我期待 24.6 的回归。

谢谢你

2 个答案:

答案 0 :(得分:2)

这个怎么样:

(from o in db.MyTableFirsts
 join p in db.MyTableSeconds on o.TheName equals p.TheName
 where p.TheName == "CBA-123" && !p.Removed &&
 (o.ReturnPeriod == 100 || o.ReturnPeriod == 10)
  select new
  {
    Maximum = Math.Max(
       Math.Max((float)(o.MaxValue1 ?? 0), (float)(o.MaxValue2 ?? 0)),
       (float)(o.MaxValue3 ?? 0)
    )
  }).OrderByDescending(o => o.Maximum).FirstOrDefault();

或者代替.OrderByDescending(o => o.Maximum).FirstOrDefault(),你可以使用.Max(o => o)

答案 1 :(得分:1)

试试这个:

(
 from o in MyTableFirst
 join p in MyTableSecond on o.TheName equals p.TheName
 where p.TheName == "CBA-123" && !p.Removed && 
 (o.Level ==100 || o.Level ==10)

 //combine all of the numbers into one list
 let listOfNumbers = new List<double?>{o.MaxValue1,o.MaxValue2,o.MaxValue3}

 //select the list
 select listOfNumbers
)
.SelectMany(c => c) //combine all the lists into one big list
.Max(c => c) //take the highst number