如何合并多个LINQ查询到一个结果集? [英] How do I combine multiple linq queries into one results set?

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

问题描述

我有一个多选复选框。取决于哪一个被选中,我想的结果结合成一个单一的查询。有点像:

I have a multi-select checkbox. Depending on which one is checked, I want to combine the results into a single query. Sort of like:

if (Checkbox1.Checked)
{
    var query1 = from t in table1 ...
}

if (Checkbox2.Checked)
{
    var query2 = from t in table2 ...
}

DataGridView1.DataSource = query1.Union(query2); // obviously doesnt
      // work since query1 and query2 are not defined in this scope.



不知道如何选择地组合这些?

Any idea how to combine these selectively?

推荐答案

假设查询是相同类型的,则可以定义的条件语句以外的查询。

Assuming the queries are of the same type, you could define the queries outside of the conditional statements.

首先,将创建同一类型作为参数的空枚举的helper方法:

First, a helper method that creates an empty enumerable of the same type as the parameter:

static IEnumerable<T> CreateEmptyEnumerable<T>(IEnumerable<T> templateQuery)
{
    return Enumerable.Empty<T>();
}



然后,新的代码:

Then, the new code:

var query1 = from t in table1 ...
var query2 = from t in table2 ...
var finalQuery = CreateEmptyEnumerable(query1);

if (Checkbox1.Checked)
{
    finalQuery = query1;
}

if (Checkbox2.Checked)
{
    finalQuery = finalQuery.Union(query2);
}

DataGridView1.DataSource = finalQuery.ToList(); // to avoid re-enumeration

这执行就好了,因为查询实际上并没有,直到他们执行再列举了,如调用了ToList()

This performs just fine because the queries aren't actually executed until they're enumerated over, as in the call to ToList().

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

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