如何合并Linq查询结果 [英] How to combine Linq query results

查看:81
本文介绍了如何合并Linq查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够向Linq查询添加数量不多的where子句.目前,我一直在尝试使用Concat()合并查询.例如:

I need to be able to add an unkown number of where clauses to a Linq query. Currently I have been trying to combine the queries using Concat(). For example:

var r1 =
    from field in db.fields
    where ID == 1
    select field;

var r2 = 
    from field in db.fields
    where ID == 2
    select field

var r3 = r1.Concat(r2);

这给了我奇怪的结果,所以我知道必须有更好的方法来做到这一点.有什么办法可以按照累积结果"来做某事;例如:

This is giving me odd results, so I know that there must be a better way to do this. Is there any way to do something along the lines of an "accumulating result"; such as:

r1 = r1 + r2

其中r1获得之前的所有结果以及r2的所有结果.这将允许我遍历"where"过滤器列表,并将其组合为OR语句.感谢任何可以提供帮助的人!

Where r1 gets all of the results it had before plus all of the results from r2. This would allow me to iterate through a list of "where" filters and combine them as an OR statement would. Thanks to anyone who can help!

推荐答案

听起来您正在寻找Union运算符:

It sounds like you are looking for the Union operator:

var r1 = Context.Fields.Where<FieldObject>(f => f.ID == 1).Select<FieldObject, Field>(f => f.Field);
var r2 = Context.Fields.Where<FieldObject>(f => f.ID == 2).Select<FieldObject, Field>(f => f.Field);
var r3 = r1.Union<Field>(r2);

这篇关于如何合并Linq查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆