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
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 besti
And to stringify the city its as simple as:
Because overriding specifically
.ToString()
automates this. You also can callhighestTempCity.ToString()
if you like.If you utilize the power of Linq though you can simplify this a lot by just doing: