LINQ查询,以检查邮政编码是否在起始和结束邮政编码的范围内



我需要检查邮政编码是否在给定的起始和结束邮政编码内,使用linq.

这是我到目前为止,但它是不正确的,有人可以指给我正确的方向吗?

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

尝试CompareTo的字符串。这能起作用吗?

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

我假定字符串的自然排序就是您所说的"between"。如果不是这样,您应该查看IComparable接口,以便对排序有更多的控制。

我也做了排他性比较。但是,您可以更改操作符以使它们包含在内。

    class Program
{
    static void Main(string[] args)
    {
        var postcode = "B";
        var stations = DestinationStation.GetDestinationStations();
        var query = from s in stations
                    where postcode.CompareTo(s.FromPostcode) > 0 && postcode.CompareTo(s.ToPostcode) < 0
                    select s;
        Console.WriteLine(query.ToList());
    }
}
public class DestinationStation
{
    public string FromPostcode;
    public string ToPostcode;
    public static List<DestinationStation> GetDestinationStations()
    {
        return new List<DestinationStation> {   new DestinationStation {FromPostcode = "A", ToPostcode = "C"},
                                                new DestinationStation {FromPostcode = "A", ToPostcode = "A"},
                                                new DestinationStation {FromPostcode = "C", ToPostcode = "C"},
                                                new DestinationStation {FromPostcode = "C", ToPostcode = "A"},
        };
    }
}

假设您使用的邮政编码是整数或类似的(并非所有邮政编码都是整数,例如英国邮政编码就像SW1A 1AA)。

Console.WriteLine( stations.Any(station => postCode >= station.FromPostcode && station <= station.ToPostcode) );
编辑:

由于英国邮政编码定义了四个不同级别的地理单位,因此您需要将组成部分分开,以便进行比较。

我有一个列表,每个DestinationStation对象都有一个FromPostcode和一个ToPostcode,它们是字符串。我需要检查给定的邮政编码是否在任何 FromPostcodes和ToPostcodes为给定的DestinationStation对象…有意义吗?

(重点)

听起来你想使用Any操作符。如果找到true,则返回'any',否则返回false

List<DestinationStation> stations = DestinationStation.GetDestinationStations(); 
var exists = stations.Any(s => 
    postcode <= s.FromPostcode && postcode >= s.ToPostcode);
if (exists)
    Console.WriteLine("It's within a range");

如果您想要查找您的邮政编码是在哪个范围内找到的,请执行where/single/first。

var all = stations.Where(s => 
    postcode <= s.FromPostcode && postcode >= s.ToPostcode);
var first = stations.First(s => 
    postcode <= s.FromPostcode && postcode >= s.ToPostcode);
var only = stations.Single(s => 
    postcode <= s.FromPostcode && postcode >= s.ToPostcode);

相关内容

最新更新