如何解决如何将数据表中的 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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。