QiangHao
QiangHao

Reputation: 3

How to select specific range of data column with C#

I am trying to display several data, but I cannot select the column that I want. My code will produce all of the column data values. I have 9 columns in data table (zero-based), and I just want to get the data from column 3 till column 9. Grateful for any kind of insight!

foreach (DataColumn column in dt.Columns)
    {
        int i = dt.Columns.IndexOf(column);
        int colCount = dt.Columns.Count;

        for (i = 3; i < colCount; i++)
            {
                html.Append("<div class='col col-" + column.Ordinal + "' data-label='" + column.ColumnName + "'>");
                html.Append(row[column.ColumnName]);
                html.Append("</div>");
            }
    }

Upvotes: 0

Views: 1043

Answers (3)

anilcemsimsek
anilcemsimsek

Reputation: 814

This answer including how to do what you want with Linq extension methods.

foreach (DataColumn column in dt.Columns.Cast<DataColumn>().Skip(3))
{
    html.Append("<div class='col col-" + column.Ordinal + "' data-label='" + column.ColumnName + "'>");
    html.Append(row[column.ColumnName]);
    html.Append("</div>");
}

Upvotes: 1

neelesh bodgal
neelesh bodgal

Reputation: 662

Check the snippet

        for (int i = 3; i < dt.Columns.Count; i++)
        {
            var column = dt.Columns[i];
            // more code
        }

Using LINQ you can achieve the same

        //This requires namespace using System.Linq;
        foreach (var column in dt.Columns.OfType<DataColumn>().Skip(3))
        {
            // more code
        }

Upvotes: 0

LeiMagnus
LeiMagnus

Reputation: 311

The problem seems to be that you have two loops. Wouldn't the below code achieve what you want?

int colCount = dt.Columns.Count
for (i = 3; i < colCount; i++)
        {
            DataColumn column = dt.Columns[i];

            html.Append("<div class='col col-" + column.Ordinal + "' data-label='" + column.ColumnName + "'>");
            html.Append(row[column.ColumnName]);
            html.Append("</div>");
        }

Upvotes: 0

Related Questions