0

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

因此,如果我的邮政编码为 51235,我需要来自 5 个较高邮政编码和较低邮政编码的产品,这对 linq 是否可行?

希望有人可以帮助

4

3 回答 3

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)
                );

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

于 2012-05-04T10:28:04.273 回答
0

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

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

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

container.Products.Where(w => (w.ZipCode == zipCode - 5) || (w.ZipCode == zipCode + 5) || (w.ZipCode == zipCode + 5));
于 2012-05-04T10:27:28.330 回答
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 );
于 2012-05-04T10:35:39.820 回答