Linq,选择值+ - 值

时间:2012-05-04 10:19:49

标签: c# linq

我需要在产品表上进行选择。 该产品有一个名为ZipCode的列 我需要从特定的邮政编码中获取产品,并且5个邮政编码高于和低于所选的邮政编码

所以,如果我有邮编51235 我需要5个更高的zipcodes和更低的zipcodes的产品,这可以用linq吗?

希望有人可以提供帮助

3 个答案:

答案 0 :(得分:1)

可能是这样的:

var zip = 51235;
context.Products.Where(p => p.ZipCode >= zip - 5 && p.ZipCode <= zip +5); 

或者像这样:

var zip = 51235;
var products = from p in context.Products
where p.ZipCode >= zip -5 && p.ZipCode <= zip + 5
select p;

更新:

如果你想在一个声明中完成所有这些,你可以这样做:

        var products = Products.Where(p1 => 
                Products.Select(p2 => p2.ZipCode)
                        .Distinct()
                        .Where(p3 => p3 >= zipCode)
                        .Take(4)
                        .Union(
                            Products.Select(p4 => p4.ZipCode)
                            .Distinct()
                            .Where(p5 => p5 < zipCode)
                            .Take(3)
                        ).Contains(p1.ZipCode)
                );

但是将它分成不同的语句以使其更具可读性可能更容易。

答案 1 :(得分:0)

在zipcode-5和zipcode + 5之间获取产品

container.Products.Where(w => (w.ZipCode > zipCode - 5) && (w.ZipCode < zipCode + 5));

要让产品的邮政编码完全等于zipcode +/- 5和当前的邮政编码。

container.Products.Where(w => (w.ZipCode == zipCode - 5) || (w.ZipCode == zipCode + 5) || (w.ZipCode == zipCode + 5));

答案 2 :(得分:0)

你可以使用,

var collectionEqualToZipCode = SourceCollection.Where(source=> source.Zip == SelectedZip);

int lessZipCodesTaken = 0;
int greaterZipCodesCountTaken = 0;
var collectionlessthanOrGreaterthanZipCode = SourceCollection.TakeWhile(source => 
(source.Zip < SelectedZip && lessZipCodesTaken++ < 5) ||
(source.Zip > SelectedZip && greaterZipCodesCountTaken ++ < 5));
FinalCOllection.AddRange(collectionEqualToZipCode);
FinalCOllection.AddRange(collectionlessthanOrGreaterthanZipCode );