Michael Michael - 1 month ago 6
C# Question

How to create Linq extension that get two parameters?

I need to write linq extension that creates and returns data table from int array.

Here the logic that have to be used inside extension.

private DataTable CreateDataTable(string colName, int[] items)
{
DataTable dt = new DataTable();
dt.Columns.Add(colName, typeof(int));
foreach (int item in items)
{
dt.Rows.Add(item);
}
return dt;
}


How can I make extension that have two parameters columnName and int array?

Answer

Like this:

public static DataTable CreateDataTable(this IEnumerable<int> items, string colName)
{
    DataTable dt = new DataTable();
    dt.Columns.Add(colName, typeof(int));
    foreach (int item in items)
    {
        dt.Rows.Add(item);
    }
    return dt;
}

The method just needs to be wrapped in a static class, and the job is done!

Comments