【问题标题】:how to Order a DataTable By more than one condition using AsEnumerable().OrderBy?如何使用 AsEnumerable().OrderBy 按多个条件对 DataTable 进行排序?
【发布时间】:2012-07-29 00:00:57
【问题描述】:

就像在 TSQL 中一样:

select * from aTable where (aCondition) order by AnIntegerField desc, ADateField 

如何使用以下方法对 DataTable 进行排序:

dt.AsEnumerable().OrderBy(--two conditions --)

【问题讨论】:

  • 您确实意识到AsEnumerable() 意味着所有排序都将在内存中完成,对吧?

标签: c# .net vb.net linq datatable


【解决方案1】:

您可以先使用 OrderBy,然后使用 ThenBy(升序)或 ThenByDescending(降序)。

来自 Microsoft 文档:

    string[] fruits = { "grape", "passionfruit", "banana", "mango", 
                          "orange", "raspberry", "apple", "blueberry" };

    // Sort the strings first by their length and then 
    //alphabetically by passing the identity selector function.
    IEnumerable<string> query =
        fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);

或者对于 VB(因为问题被标记为两者):

    ' Create an array of strings.
    Dim fruits() As String = _
        {"grape", "passionfruit", "banana", "mango", _
         "orange", "raspberry", "apple", "blueberry"}

    ' Sort the strings first by their length and then 
    ' alphabetically by passing the identity function.
    Dim query As IEnumerable(Of String) = _
        fruits _
        .OrderBy(Function(fruit) fruit.Length) _
        .ThenBy(Function(fruit) fruit)

【讨论】:

  • 数据表很大,需要最好的性能,你觉得会不会比使用.Select()好
  • @Ala 你不能使用Select() 进行排序。
  • @svick 根据我的研究,我发现使用AsEnumerable().OrderBy() 比Select() 好得多,如果我们考虑到性能并且在一种情况下,这就是我没有提到的原因这个问题中的Select(),我相信这里的答案是正确的,但它实际上实现了两种,你认为它是否仍然比Select() 快,请告诉我是否必须针对这个问题提出不同的问题。
  • 好的,这个答案已经解决了我的问题,我会问另一个关于性能问题的问题,
猜你喜欢
  • 2013-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多