C# find highest value in class object array without LINQ

211 views Asked by At

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

2

There are 2 answers

6
Steffen Cole Blake On

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();
3
Jerry Ohlson On

SOLVED!
I succeeded by doing like this:

//=====Highest temperature=====//
static int HighestTemp(City[] cities, int n)
{
    int highestTemp = cities[0].temp;
    var highestTempIndex = 0;



    for (int i = 1; i < n; i++)
    {
        if (highestTemp < cities[i].temp)
        {
            highestTemp = cities[i].temp;
            highestTempIndex = i;
        }
    }
   return highestTempIndex;
}

From what this method return I made int Index and print the result in Main

//----------City with HIGHEST temperature----------//
index = HighestTemp(cities, n);
Console.WriteLine(cities[index].ToString());