I am getting an output from a DataTable
for certain columns that have been defined in a string array
: string[] columnsToBeUnique;
var ordered = dataTable1
.AsEnumerable()
.Select(column => columnsToBeUnique.Select(name => column[name]))
.Order()
.ToArray()
;
Without the .Order()
I am getting the desired output.
The the output however is not ordered so I want to order the output. When I add the .Order()
, an error Failed to compare two elements in the array.
is thrown.
I also tried:
var ordered = dataTable1
.AsEnumerable()
.Select(column => columnsToBeUnique.Select(name => column[name]))
.OrderBy(x=>x)
.ToList();
What am I doing wrong?
I am getting an output from a DataTable
for certain columns that have been defined in a string array
: string[] columnsToBeUnique;
var ordered = dataTable1
.AsEnumerable()
.Select(column => columnsToBeUnique.Select(name => column[name]))
.Order()
.ToArray()
;
Without the .Order()
I am getting the desired output.
The the output however is not ordered so I want to order the output. When I add the .Order()
, an error Failed to compare two elements in the array.
is thrown.
I also tried:
var ordered = dataTable1
.AsEnumerable()
.Select(column => columnsToBeUnique.Select(name => column[name]))
.OrderBy(x=>x)
.ToList();
What am I doing wrong?
Share Improve this question edited 20 hours ago jonrsharpe 122k30 gold badges268 silver badges475 bronze badges asked 20 hours ago Rico StrydomRico Strydom 6111 gold badge9 silver badges28 bronze badges 4 |1 Answer
Reset to default 3The error message you're getting is because the object you're trying to order is an IEnumerable<object>
(or similar) and .NET
doesn't know how to compare two sequences by default.
You are selecting a sequence of values per row (via columnsToBeUnique.Select(...)
), which results in an IEnumerable<object>
per row. But IEnumerable<object>
doesn't implement IComparable
so .Order()
or .OrderBy(x => x)
doesn't know how to sort it.
Solve this by using a similar type:
Join the values into a String:
var ordered = dataTable1
.AsEnumerable()
.Select(row => string.Join("|", columnsToBeUnique.Select(col => row[col]?.ToString())))
.OrderBy(x => x)
.ToList();
Use ValueTuple if you know how many columns:
var ordered = dataTable1
.AsEnumerable()
.Select(row => (
columnsToBeUnique.Length > 0 ? row[columnsToBeUnique[0]] : null,
columnsToBeUnique.Length > 1 ? row[columnsToBeUnique[1]] : null,
columnsToBeUnique.Length > 2 ? row[columnsToBeUnique[2]] : null
))
.OrderBy(x => x)
.ToList();
The second solution would only work if columnsToBeUnique
has a fixed number of columns.
AsEnumerable()
, the item in theSelect()
call is a row, not a column. Additionally, you should probably also skip theToList()
/ToArray()
call, and just keep the result as an Enumerable until you really need the array or list. – Joel Coehoorn Commented 20 hours ago