在这种情况下可以构建单个 LINQ 查询表达式吗?
我面临着一个场景,我必须根据许多对象过滤单个对象。
举例来说,我有一个 Grocery 对象,其中包含 Fruit 和 Vegetable 属性。然后我有单独的水果和蔬菜对象。
我的目标是这样的:
var groceryList = from grocery in Grocery.ToList()
from fruit in Fruit.ToList()
from veggie in Vegetable.ToList()
where (grocery.fruitId = fruit.fruitId)
where (grocery.vegId = veggie.vegId)
select (grocery);
我面临的问题是水果和蔬菜对象为空时。 空,我的意思是它们的列表计数为 0,并且我只想在填充过滤器列表时应用过滤器。
我也不能能够使用类似的东西,因为对象为空:
var groceryList = from grocery in Grocery.ToList()
from fruit in Fruit.ToList()
from veggie in Vegetable.ToList()
where (grocery.fruitId = fruit.fruitId || fruit.fruitId == String.Empty)
where (grocery.vegId = veggie.vegId || veggie.vegId == String.Empty)
select (grocery);
所以,我打算检查水果和蔬菜列表计数...并在连续过滤的 Grocery 对象上将它们作为单独的表达式进行过滤。
但是,如果单个查询表达式中存在空对象,是否有办法仍然获取列表?
I am facing a scenario where I have to filter a single object based on many objects.
For sake of example, I have a Grocery object which comprises of both Fruit and Vegetable properties. Then I have the individual Fruit and Vegetable objects.
My objective is this:
var groceryList = from grocery in Grocery.ToList()
from fruit in Fruit.ToList()
from veggie in Vegetable.ToList()
where (grocery.fruitId = fruit.fruitId)
where (grocery.vegId = veggie.vegId)
select (grocery);
The problem I am facing is when Fruit and Vegetable objects are empty.
By empty, I mean their list count is 0 and I want to apply the filter only if the filter list is populated.
I am also NOT able to use something like since objects are null:
var groceryList = from grocery in Grocery.ToList()
from fruit in Fruit.ToList()
from veggie in Vegetable.ToList()
where (grocery.fruitId = fruit.fruitId || fruit.fruitId == String.Empty)
where (grocery.vegId = veggie.vegId || veggie.vegId == String.Empty)
select (grocery);
So, I intend to check for Fruit and Vegetable list count...and filter them as separate expressions on successively filtered Grocery objects.
But is there a way to still get the list in case of null objects in a single query expression?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为 LINQ GroupJoin 运算符 会在这里为您提供帮助。它类似于 TSQL
LEFT OUTER JOIN
I think the LINQ GroupJoin operator will help you here. It's similar to the TSQL
LEFT OUTER JOIN
尝试如下操作:
在我所说的设置杂货属性的地方,您可以从选择器的 g、f、v 变量设置杂货对象的属性。感兴趣的显然是设置
g.fruitId = f.fruitId
和g.vegeId = v.vegeId
。Try something like the following:
Where I have said set grocery properties you can set the properties of the grocery object from the g, f, v variables of the selector. Of interest will obviouly be setting
g.fruitId = f.fruitId
andg.vegeId = v.vegeId
.为此,您必须使用 leftouter join(如 TSQL)。在技巧的查询下方
编辑:
这是示例结果
1 1 ss
2 2 aa
3 3
You have to use leftouter join (like TSQL) for this. below the query for the trick
EDIT:
this is the sample result
1 1 s s
2 2 a a
3 3