【问题标题】:How to insert x number of datarows from a datatable into a list?如何将数据表中的 x 个数据行插入到列表中?
【发布时间】:2021-04-01 08:33:35
【问题描述】:

我目前正在使用现有的一段代码,它可以将指定数据表列中的所有数据行作为整数插入到列表中。但是,在当前代码中,我只能添加所有数据行。我希望能够插入 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,4,7,该怎么办?

【问题讨论】:

    标签: c# datatable datarow


    【解决方案1】:

    您可以通过使用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();
    }
    

    【讨论】:

    • 感谢您的回答。然而,这个解决方案不是动态的。我以这个数据表为例。在实际情况下,我只想打印前 9 行数据。有什么解决办法吗?
    • 这是一个可以构建的简单示例。您可以创建一个方法,您可以在其中传递相关参数,然后您可以进行相应的过滤
    • 我可以用数据行索引替换 54 吗?
    • @JamesVH 我已经更新了我的答案。 Take 方法将根据传入的参数值获取 N 个项目。我希望这涵盖了您所追求的内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    相关资源
    最近更新 更多