O.O
O.O

Reputation: 11287

DataTable Custom LINQ OrderBy

I keep getting object not set to an instance of an object and I'm not sure why.

SortColumn datatype string Data: "123|bob", DBNull.Value, "234|sam", "345|jim"

I have this so far:

table = table.AsEnumerable().OrderBy(
   o => o.Field<object>(sortColumn) == 
          DBNull.Value ? 99999 : o.Field<string>(sortColumn).Split('|')[0].TryParse(0)
          ).CopyToDataTable();

public static int TryParse(this string input, int valueIfNotConverted)
{
    int value;
    if (Int32.TryParse(input, out value))
    {
        return value;
    }
    return valueIfNotConverted;
}

Basically want to sort the part before | in ascending order (CopyToDataTable() returns the sorted table)

Upvotes: 1

Views: 4104

Answers (1)

Bryan Watts
Bryan Watts

Reputation: 45445

I believe the Field<> extension method handles DBNull for you, so you can just check for a null value (more information):

... o.Field<object>(sortColumn) == null ? 99999 ...

On a side note, you can avoid the double field access by selecting all of the column values first, then doing the split:

table
    .AsEnumerable()
    .Select(row => row.Field<string>(sortColumn))
    .OrderBy(value => value == null ? 99999 : Convert.ToInt32(value.Split('|').First()));

Upvotes: 2

Related Questions