简体   繁体   English

在C#中测试空的DataRow

[英]Test for an empty DataRow in C#

what I'm trying to do: I have a large datatable, and I'm going through a list of strings where some of them are in the datatable and some aren't. 我正在尝试做的是:我有一个大的数据表,并且要遍历一个字符串列表,其中一些字符串在数据表中,而有些不在。 I need to make a list of those that are, and count those that aren't. 我需要列出其中的一个,并计算不存在的那些。 This is my code part: 这是我的代码部分:

DataRow[] foundRows;

foundRows = DTgesamt.Select("SAP_NR like '%"+SAP+"%'");
if (AreAllCellsEmpty(foundRows[0]) == false && !(foundRows[0]==null))
{
    list.Add(SAP);
}
else
{
   notfound++; 
}


public static bool AreAllCellsEmpty(DataRow row)
{
    if (row == null) throw new ArgumentNullException("row");

    for (int i = row.Table.Columns.Count - 1; i >= 0; i--)
    {
        if (!row.IsNull(i))
        {
            return false;
        }
    }

    return true;
}

DTgesamt ist a large DataTable. DTgesamt包含一个大型DataTable。 "SAP" is a string that is in the first column of the DataTable, but not all of them are included. “ SAP”是数据表第一列中的字符串,但并非全部包含在内。 I want to count the unfound ones with the int "notfound". 我想用int“ notfound”来计算未找到的那些。 The problem is, the Select returns an empty DataRow {System.Data.DataRow[0]} when it finds nothing. 问题是,Select未找到任何内容时将返回一个空的DataRow {System.Data.DataRow [0]}。 I'm getting the errormessage Index out of array area. 我将errormessage索引移出了数组区域。 The two statements in the if-clause are what I read on the internet but they don't work. 如果从句中的两个陈述是我在互联网上阅读的,但它们不起作用。 With only the 2nd statement it just adds all numbers to the list, with the first it still gives this error. 仅使用第二条语句,它只是将所有数字添加到列表中,而使用第一条语句仍会给出此错误。 Thanks for any help :) 谢谢你的帮助 :)

check count of items in foundRows array to avoid IndexOutOfRange exception 检查foundRows数组中的项目计数,以避免IndexOutOfRange异常

foundRows = DTgesamt.Select("SAP_NR like '%"+SAP+"%'");
if (foundRows.Length > 0 && AreAllCellsEmpty(foundRows[0])==false)    
    list.Add(SAP);    
else    
    notfound++;    

The found cells cannot be empty. 找到的单元格不能为空。 Your select statement would be wrong. 您的选择陈述将是错误的。 So what you actually need is: 因此,您真正需要的是:

if (DTgesamt.Select("SAP_NR like '%"+SAP+"%'").Any())
{
    list.Add(SAP);
}
else
{
   notfound++; 
}

You probably don't even need the counter, when you can calculate the missed records based on how many SAP numbers you had and how many results you got in list . 当您可以根据拥有的SAP编号和list获得的结果来计算丢失的记录时,甚至可能不需要计数器。

If you have an original list or array of SAP numbers, you could shorten your whole loop to: 如果您有原始的SAP编号列表或数组,则可以将整个循环缩短为:

var numbersInTable = originalNumbers.Where(sap => DTgesamt.Select("SAP_NR like '%"+sap+"%'").Any()).ToList();

var notFound = originalNumbers.Count - numbersInTable.Count;

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

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