Home > Blockchain >  C# find highest value in class object array without LINQ
C# find highest value in class object array without LINQ

Time:05-09

This is for my school project and therefor I need to code without LINQ methods etc. I'm trying to show which city has the highest temperature by finding the highest temp and then print it together with the city name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class City
{
    public string name { get; set; }
    public int temp { get; set; }


    public override string ToString()
    {
        return $"CITY:\t{name}\nTEMP:\t{temp}°C\n";
    }
}

I want to use Tostring() to print.

//=====Highest Temperature=====//
static void HighestTemp(City[] cities)
{
    int highest = cities[0].temp;
    
    for (int i = 1; i < cities.Length; i  )
    {
        if (highest < cities[i].temp)
        {
            highest = cities[i].temp;          
        } 
    }
    
}

I've found the highest temperature. But the question is: How do I print it with ToString()?? I want both cities[i].name and cities[i].temp

CodePudding user response:

Your issue is you found the highest temp, not the city with the highest temp.

Without using Linq or any of the shortcut methods like .OrderBy(..) or .OrderByDescending(..), you can simply just store a second variable that tracks your best i

int highestTemp = cities[0].temp;
int highestTempIndex = 0;

for (int i = 1; i < cities.Length; i  )
{
    if (highest < cities[i].temp)
    {
        highest = cities[i].temp;
        highestTempIndex = i;          
    } 
}

var highestTempCity = cities[highestTempIndex];

And to stringify the city its as simple as:

$"{highestTempCity}"

Because overriding specifically .ToString() automates this. You also can call highestTempCity.ToString() if you like.

If you utilize the power of Linq though you can simplify this a lot by just doing:

var highestTempCity = cities.OrderByDescending(city => city.temp).First();

CodePudding user response:

Try Console.WriteLine(cities[i].toString())

OR

Try Console.WriteLine(cities[i])

  • Related