【问题标题】:How to order DataColumns?如何订购数据列?
【发布时间】:2012-01-29 20:42:21
【问题描述】:

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

“姓名”、“年龄”、“abc (5/2010)”、“def (12/2010)”“efa (5/2011)”“ace (12/2011)”

我如何使用 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);
}

【问题讨论】:

    标签: c# linq .net-4.0 ado.net


    【解决方案1】:

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

    【讨论】:

    • 哦,是的,我刚刚在您发布的同一时间找到了答案。
    猜你喜欢
    • 2021-11-27
    • 2018-09-09
    • 1970-01-01
    • 2017-01-26
    • 2022-11-07
    • 1970-01-01
    • 2020-01-28
    • 2021-07-11
    相关资源
    最近更新 更多