简体   繁体   English

DataTable扩展方法C#

[英]DataTable Extension methods C#

I have a method to perform operation in Datatable. 我有一种方法可以在Datatable中执行操作。

public DataTable SetColumnsOrder(DataTable table, String[] columnNames)
    {
        int columnIndex = 0;
        foreach (var columnName in columnNames)
        {
            if (table.Columns.Contains(columnName))
            {
                table.Columns[columnName].SetOrdinal(columnIndex);
                columnIndex++;
            }
        } return table;
    }

To access this method I need to do like this 要访问此方法,我需要这样做

dt = SetColumnsOrder(dt,colNames);

Instead of doing like this, how to create a function to call it like below in c# 而不是这样做,而是如何在c#中创建一个函数来像下面这样调用它

dt.SetColumnOrder(colNames);

where the function should take dt as input to perform operations and store back in same dt. 该函数应以dt作为输入来执行操作并将其存储回同一dt中。

You would need to use an extension method like so: 您将需要使用如下扩展方法:

public static class DataTableExtensions
{
    public static DataTable SetColumnsOrder(this DataTable table, string[] columnNames)
    {
        int columnIndex = 0;
        foreach (var columnName in columnNames)
        {
            if (table.Columns.Contains(columnName))
            {
                table.Columns[columnName].SetOrdinal(columnIndex);
                columnIndex++;
            }
        }
        return table;
    }
}

Usage would be: 用法是:

dt.SetColumnsOrder(columnNames);

And since you're modifying the DataTable, which is a reference type. 并且由于您正在修改DataTable,它是一种引用类型。 You can use void as the return type and just access the sorted dt variable 您可以使用void作为返回类型,只需访问已排序的dt变量

First of all, you don't need to return the same DataTable that you pass in. You could change your method signature to: 首先,您不需要返回传递的同一数据表。您可以将方法签名更改为:

public void SetColumnsOrder(DataTable table, String[] columnNames)

and remove the return , and it would still work the same (obviously you'd call it like SetColumnsOrder(dt,colNames); instead of dt = SetColumnsOrder(dt,colNames); . And you should do that, because it's less confusing design. 并删除return ,它仍然可以正常工作(很显然,您将其命名为SetColumnsOrder(dt,colNames);而不是dt = SetColumnsOrder(dt,colNames);应该这样做,因为它不易混淆设计。

Then, in order to call it as an extension method, just change the signature again, to: 然后,为了将其作为扩展方法进行调用,只需再次将签名更改为:

public static void SetColumnsOrder(this DataTable table, String[] columnNames)

And now you can use it like dt.SetColumnOrder(colNames); 现在,您可以像dt.SetColumnOrder(colNames);一样使用它dt.SetColumnOrder(colNames); .

Change your signature from 从更改您的签名

public DataTable SetColumnsOrder(DataTable table, String[] columnNames)

to

public static DataTable SetColumnsOrder(this DataTable table, String[] columnNames)

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

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