【问题标题】:find the row number of a datatable column containing specific value C#查找包含特定值 C# 的数据表列的行号
【发布时间】:2019-04-04 13:37:46
【问题描述】:

我在 C# 中有一个数据表,其中包含一个名为 Point 的列,其中包含各种整数值。如何找到等于特定值的第一行的行号。例如。也许我想找到数字 52 第一次出现在点列中,它首先出现在第 10 行。如何找到值 10?

请注意,我想在该位置找到行号而不是另一列的值,因此为什么这个问题不同于: Find row in datatable with specific id

【问题讨论】:

标签: c# datatable


【解决方案1】:

for 循环可能是最简单的方法。此答案返回DataTable 中与特定值匹配的行的索引(行号)。

int firstRow = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
    var row = dt.Rows[i];
    int point = Convert.ToInt32(row["Point"].ToString());
    if (point == 52)
    {
        // i is the first row matching your condition
        firstRow = i;
        break;
    }
}

【讨论】:

    【解决方案2】:

    以下内容可能对您有用:

    DataTable table = new DataTable("SomeData");
    table.Columns.Add("Point", typeof(int));
    table.Rows.Add(5);
    table.Rows.Add(7);
    table.Rows.Add(52);
    table.Rows.Add(2);
    table.Rows.Add(1);
    table.Rows.Add(4);
    table.Rows.Add(9);
    
    var row = table.AsEnumerable().Select((r, i) => new { Row = r, Index = i }).Where(x => (int)x.Row["Point"] == 52).FirstOrDefault();
    int rowNumber = 0;
    if (row != null)
        rowNumber = row.Index + 1;
    

    请注意,在此示例中,我给出的是行号,而不是从零开始的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 2016-04-20
      • 2020-08-30
      相关资源
      最近更新 更多