mADy1270
mADy1270

Reputation: 55

Get Maximum Value from multiple rows of multiple columns using LINQ?

I'm using LINQPad to evaluate my linq query. My query goes like this:

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
}


This query can return 0 or some number of rows.

In LINQPad, it return me something like this:

HMax1   HMax2   HMax3
21.1        null         22.5
null         24.6        11.5

Now, how am I going to get the Maximum value out for these return rows & columns?
I'm expecting return of 24.6.

Thank You

Upvotes: 2

Views: 2564

Answers (2)

Zoran Causev
Zoran Causev

Reputation: 360

How about this:

(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();

Or instead of .OrderByDescending(o => o.Maximum).FirstOrDefault(), you can use .Max(o => o)

Upvotes: 2

Jens Kloster
Jens Kloster

Reputation: 11277

Try this:

(
 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

Upvotes: 1

Related Questions