Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple value comparisons in Linq to SQL

Has anyone got a tidier way of doing this with linq to entities?

I am trying to get the item in each group that has the highest X, Y or Z e.g. Max( X, Y, Z )

var points = from g in groupedData
             from ep in g
             where (ep.X > ep.Y ?
                               ep.X > ep.Z ? ep.X : ep.Z
                             : ep.Y > ep.Z ? ep.Y : ep.Z)
             == g.Max(e => e.X > e.Y ?
                           e.X > e.Z ? e.X : e.Z
                             : e.Y > e.Z ? e.Y : e.Z)
             select ep;
like image 655
Void Avatar asked Aug 23 '26 14:08

Void


1 Answers

var points = from g in groupedData
             let gMax = g.Max(e => e.X > e.Y ?
                                    (e.X > e.Z ? e.X : e.Z)
                                  : (e.Y > e.Z ? e.Y : e.Z))
             from ep in g
             where ep.X == gMax
                   || ep.Y == gMax
                   || ep.Z == gMax
             select ep;

PS : Linq2SQL or Linq2Entities ? Because you flagged "EF" !

Edit : I've just tested this with success :

var points = from g in groupedData
             let gMax = g.Max(e => new int[] { e.X, e.Y, e.Z }.Max())
             from ep in g
             where ep.X == gMax
                   || ep.Y == gMax
                   || ep.Z == gMax
             select ep;

Do you confirm it works in your case ?

like image 107
JYL Avatar answered Aug 26 '26 03:08

JYL