PeterJ
PeterJ

Reputation: 373

Extension method for Sorting a DataTable

I am trying to sort a DataTable with an extensionmethod. If used in the code body this works fine:

DataView dv = dtSensors.DefaultView;
dv.Sort = "DeviceName";
dtSensors = dv.ToTable();

However, used like this it does not:

public static void SortTable(this DataTable dt, string sortColumn)
{
     DataView dv = dt.DefaultView;
     dv.Sort = sortColumn;
     dt = dv.ToTable();
}

Why would the extension method not work in this case?

Thanks,

Peter

Upvotes: 0

Views: 158

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503779

You're assigning a new value to dt within the method, but that won't change the variable used when you call the method - it's a value parameter.

As a simple example of that:

using System;

static class Int32Extensions
{
    // This doesn't do what you might expect it to!
    public static void Increment(this int x)
    {
        x = x + 1;
    }
}

class Test
{
    static void Main()
    {
        int x = 10;
        x.Increment();
        Console.WriteLine(x); // Still 10
    }
}

I would personally write the method to return the new table, modifying the name appropriately:

public static DataTable SortedBy(this DataTable dt, string sortColumn)
{
     DataView dv = dt.DefaultView;
     dv.Sort = sortColumn;
     return dv.ToTable();
}

Then use it as:

table = table.SortedBy("columnName");

I'm slightly concerned as to whether the modification to DefaultView will persist in the original table - it's not ideal to have a method like this mutate the original object. It depends whether DefaultView creates a new view each time it's called...

Upvotes: 2

Related Questions