Home > database >  How to find largest property in List?
How to find largest property in List?

Time:07-19

I have linq expression "Where" that may returns several rows:

var checkedPrices = prices.Where(...).ToList();

As there are several rows, retrieves from db => i want to take the largest string from this list of rows.

Also there is a case when one of the fields may have same lenght, so i tried to find the largest from another field.

int countPrices = checkedPrices.Count();

if (checkedPrices == 0)
{
    checkedPrices = null;
}
else if (checkedPrices == 1) 
{
    checkedPrices = checkedPrices.Take(1).ToList();
}
else if (countFixedPrices > 1)
{
    var maxPrices1 = checkedPrices.Max(i => i.Field1.Length);
    if (maxPrices1 > 1)
    {
        var maxPrices2 = checkedPrices.Max(i => i.Field2.Length);
        checkedPrices = checkedPrices.IndexOf(maxPrices2 );
    }

    checkedPrices = checkedPrices .ElementAt(maxPrices2);
}

So, i have an issue in the last "else if". My logic was to find the max largest of Field1. If there is the only one largest field - rewrite it to the "Where" expression (checkedPrices). If there is not only one max largest of Field1 => take the largest from Field2.

The problem of mine is i'm confused how could i take the row data from the largest Field1/Field2.

This part of code is ridiculously bad(doesnt even compile):

if (maxPrices1 > 1)
{
    var maxPrices2 = checkedPrices.Max(i => i.Field2.Length);
    checkedPrices = checkedPrices.IndexOf(maxPrices2 );
}

checkedPrices = checkedPrices .ElementAt(maxPrices2);

CodePudding user response:

Since it seems you need only one price I would recommend just write correct query to fetch it only. You can order items (with LINQ's OrderByDescending and ThenByDescending) and the take the top one:

var checkedPrice = prices
    .Where(...)
    .OrderByDescending(c => c.Field1.Length)
    .ThenByDescending(c => c.Field1.Length)
    .FirstOrDefault();
  •  Tags:  
  • c#
  • Related