结果与空 LINQ 查询的并集
在数据库中,我有一些产品和价格。 我需要寻找价格限制。问题是可能有几个限制。例如,0 - 500 $ 1500 - $ 2000
如何合并此 LINQ 查询
var products = from product in db.Products
where product.Price >= 0 and product.Price <= 500
var products = from product in db.Products
where product.Price >= 1500 and product.Price <= 2000
我的变体:
IQueryable<Deal> allResults = null;
for(var i = 0; i < price.Length - 1; i = i + 2)
{
decimal start,end;
decimal.TryParse(price[i], out start);
decimal.TryParse(price[i+1], out end);
var tempResults = from product in query
where (product.DiscountPrice >= start && product.DiscountPrice <= end)
select product;
tempResults.Union(allResults);
}
如何创建一个空查询来连接?
In the database, I have some of the products and prices.
I need to search for the price limits. The problem is that there may be several limits. For example, 0 - 500 $ 1500 - $ 2000
How to merge this LINQ queries
var products = from product in db.Products
where product.Price >= 0 and product.Price <= 500
var products = from product in db.Products
where product.Price >= 1500 and product.Price <= 2000
My varriant:
IQueryable<Deal> allResults = null;
for(var i = 0; i < price.Length - 1; i = i + 2)
{
decimal start,end;
decimal.TryParse(price[i], out start);
decimal.TryParse(price[i+1], out end);
var tempResults = from product in query
where (product.DiscountPrice >= start && product.DiscountPrice <= end)
select product;
tempResults.Union(allResults);
}
how to create an empty query to join ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是合并条件:
另一种方法是使用
Union
或Concat
:调整代码可以做到:
您不需要空查询来合并,您可以添加一个特殊情况来测试这是否是第一个查询。
但我不太喜欢该代码,因为它混合了两个问题:查询的构造和查询的合并。所以我把它分成两部分:
One way is to merge the conditions:
Another is to use
Union
orConcat
:Adapting your code on can do:
You don't need an empty query in to merge with, you can just add a special case that tests if this is the first query.
But I don't like that code much, because it mixes two concerns: The construction of the queries, and the merging of the queries. So I'd split it in two:
您可以使用
Enumerable.Empty().AsQueryable()
创建空查询。您的代码中存在的问题:
Union
不会更改您作为参数传递给它的任何序列;相反,它创建一个返回的新序列。因此,您应该将tempResults.Union(allResults)
操作的结果分配给allResults
。这是一些示例代码(未经测试):
You can create an empty query using
Enumerable.Empty<T>().AsQueryable()
.An issue you have in your code:
Union
does not alter any of the sequences that you pass to it as parameters; rather, it creates a new sequence which it returns. Thus, you should be assigning the result of yourtempResults.Union(allResults)
operation toallResults
.Here is some sample code (not tested):