简体   繁体   中英

DataTable Extension methods C#

I have a method to perform operation in 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#

dt.SetColumnOrder(colNames);

where the function should take dt as input to perform operations and store back in same 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. You can use void as the return type and just access the sorted dt variable

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.

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

Change your signature from

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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