如何订购DataColumns

本文关键字:DataColumns 何订购 | 更新日期: 2023-09-27 18:21:41

我有以下列名,需要按括号中的日期排序:

"姓名"年龄"abc(2010年5月)"def(2010年12月)"

如何使用LINQ订购这些?

我试过这种方法。似乎我不应该用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);
}

如何订购DataColumns

OrderBy.ThenBy无法正常工作。您需要将结果分配给另一个变量。