[英]Linq, select values + - a value
I need to do a select on a product table. 我需要在产品表上进行选择。 The product has a column called ZipCode I need to get alle the products from a specific zipcode, and the 5 zipcode higher and lower than the selected zipcode
产品有一个名为ZipCode的列,我需要从特定的邮政编码中获取所有产品,以及高于或低于所选邮政编码的5个邮政编码。
so if i have the zipcode 51235 i need the products from 5 higher zipcodes and lower zipcodes, is this possible with linq? 所以,如果我有邮政编码51235,我需要5个较高的邮政编码和较低的邮政编码的产品,linq是否可以?
Hope someone can help 希望有人能帮忙
Maybe something like: 也许像这样:
var zip = 51235;
context.Products.Where(p => p.ZipCode >= zip - 5 && p.ZipCode <= zip +5);
Or like this: 或像这样:
var zip = 51235;
var products = from p in context.Products
where p.ZipCode >= zip -5 && p.ZipCode <= zip + 5
select p;
UPDATE: 更新:
If you want to do it all in one statement you could do it like this: 如果您想在一条语句中完成所有操作,则可以这样做:
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)
);
But it might be easier to split it up into different statements to keep it more readable. 但是将其拆分为不同的语句以使其更具可读性可能更容易。
To get products between zipcode-5 and zipcode+5 在zipcode-5和zipcode + 5之间获取产品
container.Products.Where(w => (w.ZipCode > zipCode - 5) && (w.ZipCode < zipCode + 5));
To get products have their zipcodes exactly equals to zipcode +/- 5 and current zipcode. 要获得产品,其邮政编码完全等于+/- 5邮政编码和当前的邮政编码。
container.Products.Where(w => (w.ZipCode == zipCode - 5) || (w.ZipCode == zipCode + 5) || (w.ZipCode == zipCode + 5));
You can use, 您可以使用,
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.