简体   繁体   English

将一系列数据行复制到另一个数据表-C#

[英]Copy a range of data rows to another datatable - C#

I have a data table that contains 100 rows, I want to copy a range of rows(31st row to 50th row) to another data table. 我有一个包含100行的数据表,我想将一定范围的行(第31行到第50行)复制到另一个数据表。

I am following below logic. 我遵循以下逻辑。

DataTable dtNew = table.Clone();
for(int k=30; k < 50 && k < table.Rows.Count; k++)
{
     dtNew.ImportRow(table.Rows[k]);
}

Is there any better approach to do this? 有没有更好的方法可以做到这一点?

Using LINQ you can do something like: 使用LINQ您可以执行以下操作:

DataTable dtNew = table.Select().Skip(31).Take(20).CopyToDataTable();

Performance wise, using LINQ wont do any better, it however makes it more readable. 在性能方面,使用LINQ不会做得更好,但是会使其更具可读性。

EDIT: Added handling check 编辑:添加处理检查

int numOFEndrow = 20;
int numOfStartRow = 31;
if (table.Rows.Count > numOFEndrow +numOfStartRow)
{
    DataTable dtNew = table.Select().Skip(numOfStartRow).Take(numOFEndrow).CopyToDataTable();
}

If it's about readability, then a good idea would be to throw this into an extension method. 如果是关于可读性的,那么一个好主意是将其放入扩展方法中。
Without changing your logic: 在不更改逻辑的情况下:

public static class Utils
{
    public static void CopyRows(this DataTable from, DataTable to, int min, int max)
    {
        for (int i = min; i < max && i < from.Rows.Count; i++)
            to.ImportRow(from.Rows[i]);
    }
}

Then you can always reuse it without all the fancy syntax and know that it does exactly what you need if there is a concern of performance: 然后,您始终可以在没有所有花哨的语法的情况下重用它,并知道它在满足性能要求时可以完全满足您的需要:

        DataTable dt1 = new DataTable();
        DataTable dt2 = new DataTable();
        dt1.CopyRows(dt2, 30, 50);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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