Home > database >  How can I order objects in a list?
How can I order objects in a list?

Time:10-01

I simply want to select the unit with highest damage value. I tried using linq, this is what I'm trying to do, but I get error saying "foreach statement cannot operate on variabls of type Unit because Unit does not contain public instance definition of GetEnumerator":

  foreach (Unit unit in units2.OrderByDescending(t => t.maxDamage).FirstOrDefault())
    {
       SelectUnit(unit);
    }

CodePudding user response:

FirstOrDefault returns zero or one item, so no need for the loop (but you might want to check for null)

var unit = units2.OrderByDescending(t => t.maxDamage).FirstOrDefault();
if(unit != null)
    SelectUnit(unit)
  • Related