I’ve got the following column names that I need to order by the date in the parentheses:
“Name”, “Age”, “abc (5/2010)”, “def (12/2010)” “efa (5/2011)” “ace (12/2011)”
How can I use LINQ to order these?
I tried with this method. It seems like I shouldn’t have to do all of this with LINQ:
Dictionary<DataColumn, DateTime> columns = new Dictionary<DataColumn, DateTime>();
int startIndex;
int endIndex;
for (int i = 0; i < table.Columns.Count; ++i)
{
// these columns need to be sorted
startIndex = table.Columns[i].Caption.IndexOf('(');
endIndex = table.Columns[i].Caption.IndexOf(')');
if (startIndex > 0 && endIndex > 0)
{
// create a standard date
string monthYear = table.Columns[i].Caption.Substring(
startIndex + 1, endIndex - startIndex - 1);
columns.Add(
table.Columns[i],
DateTime.Parse(monthYear.Replace("/", "/01/")).Date);
}
else
{
// all other columns should be sorted first
columns.Add(table.Columns[i], DateTime.MinValue);
}
}
// perform the LINQ order by
columns = columns.OrderBy(o => o.Value).ToDictionary(o => o.Key, o => o.Value);
// order the original table uses the dictionary
for (int i = 0; i < columns.Count; ++i)
{
table.Columns[columns.Keys.ElementAt(i).Caption].SetOrdinal(i);
}
OrderBy.ThenBy doesn’t work in place. You need to assign the result to another variable.