Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在数据表中为特定列获取具有相同值的所有单元格的开始索引和最后索引_C#_Datatable - Fatal编程技术网

C# 如何在数据表中为特定列获取具有相同值的所有单元格的开始索引和最后索引

C# 如何在数据表中为特定列获取具有相同值的所有单元格的开始索引和最后索引,c#,datatable,C#,Datatable,如何为特定列获取DataTable中具有相同值的所有单元格的开始索引和最后索引 例如,如果我的数据表如下所示: column1 column2 a 0 a 1 a 2 b 3 b 4 b 5 因此,我希望输出是第1列中a值的起始索引为0,第1列中a值的最后索引为2。 类似地,第1列中值b的开始索引和最后索引分别为3和5。是否需要这项工作 cla

如何为特定列获取DataTable中具有相同值的所有单元格的开始索引和最后索引

例如,如果我的数据表如下所示:

column1     column2
a             0
a             1
a             2
b             3
b             4
b             5
因此,我希望输出是第1列中a值的起始索引为0,第1列中a值的最后索引为2。
类似地,第1列中值b的开始索引和最后索引分别为3和5。

是否需要这项工作

class Index // Edit here
{
    public string value;
    public int first;
    public int last;
}

List<Index> indexes = new List<Index>();

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    Index ind = indexes.SingleOrDefault(i => i.value == row.Cells[0].Value.ToString()); // Remember to set the correct index of the column

    if (ind == null) // Edit here
    {
        ind = new Index(); // Edit here

        ind.value = row.Cells[0].Value.ToString(); // Remember to set the correct index of the column
        ind.first = ind.last = row.Index;

        indexes.Add(ind);
    }
    else
    {
        ind.last = row.Index;
    }
}
这将创建一个包含变量的类列表:value,first和last,这将是您要查找的值

我希望这有帮助

编辑:我对代码做了一些修改,其中“Index”是一个类而不是一个结构。这个效果更好吗


但是在第1列中也是3-5你想要一个查询返回a-0、a-2、b-3和b-5吗?不,我想要一个c逻辑,它可以循环通过数据表中的第1列,并给出第1列中类似值单元格的开始索引和最后索引。我有个主意,给我一个second@MasterXD我想他说的是DataTable不是GridView哦,射击Will fixThis可以很好地获取开始索引,但不能用于最后一个索引@就像我为datatable做的一样,你知道的,基本上是一样的。好吧,那就行了。最后一个索引是什么?和第一个索引一样。