C# 检查 DataRow 数组中是否存在值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15922826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:28:15  来源:igfitidea点击:

check if a value exists in DataRow array

c#asp.net

提问by smith269

In my application i am filtering a datatable using a filter expression and am getting a DataRow which matches the condition.Now i want to check if the value of particular column exists in any row of DataRow array.

在我的应用程序中,我正在使用过滤器表达式过滤数据表,并得到一个与条件匹配的 DataRow。现在我想检查特定列的值是否存在于 DataRow 数组的任何行中。

Code:

代码

string FilterCond1 = "id=" + getId;
DataRow[] myrow = DataTable.Select(FilterCond1);
if (myrow.Length > 0)
{
//check for size=28 in DataRow[]
}
else
{
}

I have column sizein the datatable DataTableand i want to check if any row of the DataRow array has a value 28in the column size.How can i go about it?

我在数据表中有列大小DataTable我想检查 DataRow 数组的任何行在列中是否有值28。size我该怎么做?

采纳答案by Hyman Pettinger

Try this

尝试这个

string FilterCond1 = "id=" + getId;
DataRow[] myrow = DataTable.Select(FilterCond1);
if (myrow.Length > 0)
{
  for(int i = 0; i < myrow.Length; i ++)
  {
    if(myrow[i]["size"].ToString() == "28")
    {
      // YOUR CODE HERE 
    }
  }
}
else
{
}

EDIT

编辑

Just add the condition to your filter.

只需将条件添加到您的过滤器中即可。

string FilterCond1 = "id=" + getId + " AND size=28";

Then you don't need the if(myrow[i]["size"].ToString() == "28")as you know the rows in the array are the one you want.

然后你就不需要了,if(myrow[i]["size"].ToString() == "28")因为你知道数组中的行是你想要的。

回答by Adil

You can use column collection to access particular column value within row.

您可以使用列集合来访问行内的特定列值。

if(myrow[rowIndex]["ColoumnName"].ToString() == "somevalue")

Where row index could from zero to length-1

行索引可以从零到长度 1

Editbased on comments, you can put multiple condition on column in select, check it here, and may not need to iterate.

根据评论进行编辑,可以在select中的列上设置多个条件,在这里检查,可能不需要迭代。

string FilterCond1 = "id=" + getId + " AND size = " + 28;
DataRow[] myrow = dt.Select(FilterCond1);

To iterate through rows collection

遍历行集合

for(int i=0; i < myrow.Length; i++)
{
   if(myrow[i]["size"].ToString() == "28")
   {
        //your code
   }
}

回答by Jo9876

First you should aiterate through all rows using foreach then use the below code..

首先,您应该使用 foreach 遍历所有行,然后使用以下代码..

if(myrow[row]["size"] == 28)

or

或者

int ColIndex = 3; // replace 3 with ur co. index 
if(myrow[row][ColIndex] == 28)