1

I have looked at many sites and am not able to understand how I would go about using linq to query the first couple of rows of a data-table.

I would also like to know with regards to this if the data came from an Excel file would the column references be the same? For example column F in would be the same in the datatable or a numbered reference?

1 Answer 1

5
DataTable yourDataTable = new DataTable();
var result = yourDataTable.AsEnumerable()
    .Take(2) // Select first two rows
    .Select(r =>
        new
        {
            Field1 = r.Field<int>("col1"), // Select your columns
            Field2 = r.Field<string>("col2")
            // your rest of the columns
        }
    );

If you want to select only the second row then:

var result = yourDataTable.AsEnumerable()
    .Skip(1) // skip first row
    .Take(1) // Select second row
    .Select(r =>
        new
        {
            Field1 = r.Field<int>("col1"), // Select your columns
            Field2 = r.Field<string>("col2")
            // your rest of the columns
        }
    );

EDIT:

To Select all columns, instead of specific one, just remove the Select from the statement. Something like this:

var result = yourDataTable.AsEnumerable()
    .Skip(1)  // skip first row
    .Take(1); // Select second row
Sign up to request clarification or add additional context in comments.

10 Comments

will it take the whole of the second row
@user1776590, this will take the first two Rows. Do you want to select only the second row ?
so i would have to select each of the columns indervidually not together
@user1776590 just remove Select operator - it will give you rows.
@user1776590, then remove the Select and you will get all the columns
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.