1

我需要使用 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());
4

4 回答 4

2

尝试CompareTo字符串。这行得通吗?

var query =
    from s in stations
    where postcode.CompareTo(s.FromPostcode) >= 0
    where postcode.CompareTo(s.ToPostcode) <= 1
    select s;
于 2011-11-03T01:18:56.277 回答
1

我假设字符串的自然顺序是您所说的“之间”。如果不是这样,您应该查看 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"},
        };
    }
}
于 2011-11-03T01:42:29.903 回答
0

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

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

编辑:

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

于 2011-11-03T01:30:53.893 回答
0

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

(我的重点)

听起来您想使用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);
于 2011-11-03T02:25:36.187 回答