gpt4 book ai didi

c# - 结果与空 LINQ 查询的联合

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:04 25 4
gpt4 key购买 nike

在数据库中,我有一些产品和价格。我需要搜索价格限制。问题是可能有几个限制。例如,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);
}

如何创建空查询以加入?

最佳答案

一种方法是合并条件:

var products = from product in db.Products
where (product.Price >= 0 and product.Price <= 500)||product.Price >= 1500 and product.Price <= 2000

另一种是使用UnionConcat:

var products = (from product in db.Products
where product.Price >= 0 and product.Price <= 500)
.Union(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 db.Products
where (product.DiscountPrice >= start && product.DiscountPrice <= end)
select product;
if(allResults!=null)
allResults=allResults.Union(tempResults);
else
allResults=tempResults;
}

您不需要一个空查询来合并,您可以只添加一个特殊情况来测试这是否是第一个查询。

但我不太喜欢该代码,因为它混合了两个问题:查询的构造和查询的合并。所以我把它分成两部分:

IEnumerable<Tuple<Decimal,Decimal>> ParsePrices(string[] rawPrices)
{
for(var i = 0; i < price.Length - 1; i = i + 2)
{
decimal start=decimal.Parse(price[i]);
decimal end =decimal.Parse(price[i+1]);

yield return Tuple.Create(start, end);
}

var prices=ParsePrices(rawPrices);
IEnumerable<IQueryable<Deal>> partialQueries=prices.Select( interval=>
from product in db.Products
where (product.DiscountPrice >= interval.Item1 && product.DiscountPrice <= interval.Item2)
select product;);
var mergedQuery=partialQueries.Aggregate((q1,q2)=>q1.Union(q2));

关于c# - 结果与空 LINQ 查询的联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9249074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com