简体   繁体   中英

How to insert x number of datarows from a datatable into a list?

I'm currently using an existing piece of code that can insert all data rows from a specified data table column into a list as integers. However, in the current code I can only add all data rows. I want to be able to insert x amount of data rows, how would I do this?

The code:

var dt = new DataTable
            {
                Columns = { { "Lastname", typeof(int) }, { "Firstname", typeof(int) } }
            };
            dt.Rows.Add(1, 2);
            dt.Rows.Add(4, 5);
            dt.Rows.Add(7, 4);
            dt.Rows.Add(54, 67);

            List<int> ids = new List<int>();

            foreach (DataRow row in dt.Rows)
                ids.Add((int)row[0]);
            foreach(int e in ids)
                Console.WriteLine(e);
            Console.Read();

This code will currently print out 1,4,7,54 but what if i for example only want to print 1,4,7 ?

You can achieve this by making use of linq as follows:

var result = dt.Rows.Cast<DataRow>().Where(x => x.Field<int>("Lastname") != 54).ToList();

foreach(var r in result)
{
   Console.WriteLine(r.ItemArray[0]); //This will now print out 1, 4, 7
   Console.WriteLine(r.ItemArray[1]); //This will now print out 2, 5, 4
}

Dont't forget to include the namespace using System.Linq;

Update:

public List<DataRow> GetDataRowsFromDataTable(int numberOfRows)
{
   //your dt code here
   
   return dt.Rows.Cast<DataRow>().Take(numberOfRows).ToList();
}

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