Search code examples
c#linqpostal-code

LINQ query to check if a postcode is within a range of starting and ending postcodes?


I need to check if a postcode is within a given start and end postcode, using linq.

Here is what I have so far but it's not right at all, can someone point me in the right direction?

List<DestinationStation> stations = DestinationStation.GetDestinationStations();
var query = from s in stations
            where postcode <= s.FromPostcode && postcode >= s.ToPostcode
            select s;
Console.WriteLine(query.ToList());

Solution

  • Try CompareTo for strings. Does this work?

    var query =
        from s in stations
        where postcode.CompareTo(s.FromPostcode) >= 0
        where postcode.CompareTo(s.ToPostcode) <= 1
        select s;