如何将数据表中的 x 个数据行插入到列表中?

问题描述

我目前正在使用一段现有的代码,该代码可以将指定数据表列中的所有数据行作为整数插入到列表中。但是,在当前代码中,我只能添加所有数据行。我希望能够插入 x 行数据,我该怎么做?

代码

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();

代码当前将打印出 1,4,7,54 但如果我例如只想打印 1,7 怎么办?

解决方法

您可以通过使用 linq 来实现这一点,如下所示:

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
}

不要忘记包含命名空间 using System.Linq;

更新:

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