I am writing a fuel millage calculator Currently I have a List that holds travel zones.
I want to be able to search all Items in zones and find a match i.e. if I want to travel 4 miles searching the list will return the zone for "Zone 1", If I want to travel 20 miles zone for "Zone 3" is returned, if the distance is out side any zones no matches will be returned
zones.Add(new ZoneInfo
{Cost = 25, Name = "Zone 1", Radius = 5});
zones.Add(new ZoneInfo
{Cost = 40, Name = "Zone 2", Radius = 10});
zones.Add(new ZoneInfo
{Cost = 60, Name = "Zone 3", Radius = 20});
CodePudding user response:
You need to sort all your zones according to your Radius
value and then use Find
to only get the first matched zone
const travelMiles = 5 //your defined miles
const result = zones.OrderBy(zone => zone.Radius).Find(zone => zone.Radius >= travelMiles);
if(result == null) {
//TODO: not found any matched zone with travel miles
}
If your radius zones are already in order, you don't need to sort them with OrderBy
const travelMiles = 5 //your defined miles
const result = zones.Find(zone => zone.Radius >= travelMiles);
if(result == null) {
//TODO: not found any matched zone with travel miles
}
CodePudding user response:
As I understand it, you want to return the single most ideal zone that covers the desired radius, if it exists.
This can be achieved by first filtering out all zones that are not covering your range requirement (by using .Where()
), and then selecting the most ideal zone.
As the question currently stands, it is unknown to me what "most ideal" means, but I will assume most ideal translates to having the lowest cost. Finding the one zone with the lowest cost can be found by using e.g. .MinBy()
, which returns null
when used on an empty collection (e.g. in the scenario where none of the available zones cover the desired range).
It can be implemented as follows:
var rangeToCover = 4;
ZoneInfo idealZone = zones
.Where(zone => zone.Radius >= rangeToCover)
.MinBy(zone => zone.Cost);
Both .Where()
and .MinBy()
are methods from the System.Linq
namespace. .MinBy()
requires .NET 6 (or later versions).
Example fiddle here.