Rakeshkumar Das Rakeshkumar Das - 1 year ago 71
C# Question

How to get start index and last index of all the cells having same value in a data Table for a specific column

How to get start index and last index of all the cells having same value in a DataTable for a specific column?

Such as if my DataTable looks like below:

column1 column2
a 0
a 1
a 2
b 3
b 4
b 5


So that I want the output to be start index as 0 for value
a
in
column1
and last index of 2 for value of
a
in
column1
.
Similarly, 3 and 5 for start and last index for value
b
in
column1
.

Answer Source

Would something like this work?

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;
    }
}

This should create a list of classes with the variables: value, first and last, which would be the values you're looking for.

I hope this helps.

Edit: I made some changes to the code, where 'Index' is a class and not a struct. Does this work better?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download