简体   繁体   English

如何在SQL查询中包含数组的所有元素?

[英]How to include all elements of an array in a SQL query?

Basically, the idea is to match data from one DataTable with another. 基本上,我们的想法是将来自一个DataTable的数据与另一个DataTable进行匹配。 In the first DT, there are 20 different columns in one row that I create an array from, and there is another DT with thousands of rows, two columns each. 在第一个DT中,我在一行中有20个不同的列,我从中创建一个数组,并且还有另一个DT,其中包含数千行,每行两列。 I need to select all of those rows in the second DT that are found among all of the 20 different variables in the array (so, I go row by row in the first table). 我需要选择第二个DT中所有那些在数组中所有20个不同变量中找到的行(所以,我在第一个表中逐行)。

Can I do this in one query? 我可以在一个查询中执行此操作吗?

for (int x = 0; x < 20; x++) //this fills up the array from the 20 columns of dt1
{
   numbers[x] = Convert.ToInt16(dt1.Rows[i]["n" + (x+1)]);
}
var filtered = dt2.Select("Col1 = " + (any of the numbers[]) + " AND Col2 = " + (any of the numbers[]));

So clearly the line in question is the last one. 很明显,这条线是最后一条线。 I'm not sure if it's possible to do so. 我不确定是否可以这样做。

I'm new here and I'm new to C# as well. 我是新来的,我也是C#的新手。 Thank you for your help. 谢谢您的帮助。

You could convert your data table into an enumerable and filter the data with LINQ. 您可以将数据表转换为可枚举,并使用LINQ过滤数据。

Something like this: 像这样的东西:

var filtered = dt2.AsEnumerable().Where(m => numbers.Contains(m.Col1) && numbers.Contains(m.Col2)) ; var filtered = dt2.AsEnumerable().Where(m => numbers.Contains(m.Col1) && numbers.Contains(m.Col2)) ;

You could use this SQL on DataTable : 您可以在DataTable上使用此SQL:

var numbersAsString = numbers.Select(x => x.ToString()).Aggregate((x,y) => x + "," + y);
var filtered = dt2.Select("Col1 in (" + numbersAsString  + ") AND Col2 in (" + numbersAsString  + ")");

First you create string from your Array that looks like this: '1,3,4,5' and then checks in SQL if Col1 or Col2 value is in the array. 首先,从Array中创建如下所示的字符串:'1,3,4,5',然后在SQL中检查Col1或Col2值是否在数组中。

Both of the above approaches work well. 上述两种方法都运行良好。 Without knowing whether or not your DataSets are strongly-typed, however (and using a single query instead of requiring dt1 to be projected into an array): 但是,在不知道您的DataSet是否是强类型的情况下(并且使用单个查询而不是要求将dt1投影到数组中):

var filtered = dt2.AsEnumerable().Where(row => dt1.Rows[0].ItemArray.Contains(row[0]) ||
                                               dt1.Rows[0].ItemArray.Contains(row[1]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM