简体   繁体   中英

querying datatable using linq and c#

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM