Entity Framework Select multiple columns of long data type and find the maximum value of all columns

73 Views Asked by At

I need to select 2 columns of a table which are long data type and find the largest number among both columns from the result. What I tried but not successful is the following (this has errors because its incomplete code):

public long GetMaxAddressByStation(StationType station)
{
    long maxAddress = 0;

    var addressList = (from tbl1 in Table1
                       join tbl2 in Table2 on tbl1.Guid equals tbl2.Guid
                       where tbl2.Station == station
                       select new
                              {
                                  tbl1.DataAddress, 
                                  tbl1.CommandAddress
                              }).Max(<condition>);

    return maxAddress;
}
1

There are 1 best solutions below

0
RedNeath On

The problem you hare facing by trying to use the Max() method from IEnumerable (or IQueryable, which inherits the method from the previous), is that it is supposed to be used to get the maximum element from a list, not from several values in an element of a list.

That means you will compare your sets of addresses one to the other, instead of comparing the addresses of each of your set, to keep the greatest.

To solve this issue, I would create a method somewhere (probably with private visibility, directly in the class unless you see any use in keeping it somewhere else) that would take the enumerable of address sets and return an enumerable of long:

// TheType here depends on your query. You could potentially make it more
// generic by letting your function accept <T>, and use that type instead of
// TheType I used in the signature below
private List<long> MaxAddress(IEnumerable<TheType> addressesSets) {
    List<long> maxAddresses = new List<long>();

    for (var set : addressesSets) {
        maxAddresses.Add(set.adr1 >= set.adr2? set.adr1: set.adr2); // Change the `>=` to simple `>` if you want to take the second value by default when both are identical.
    }

    return maxAdress;
}

And taking back your code, you'd call it that way:

public long GetMaxAddressByStation(StationType station)
{
    long maxAddress = 0;

    var addressList = MaxAdress(from tbl1 in Table1
                                join tbl2 in Table2 on tbl1.Guid equals tbl2.Guid
                                where tbl2.Station == station
                                select new
                                    {
                                        tbl1.DataAddress, 
                                        tbl1.CommandAddress
                                    });

    maxAddress = addressList.Max(); // I guess this is what you are trying to get?
    return maxAddress;
}