簡體   English   中英

Linq OrderBy屬性值和組

[英]Linq OrderBy Attribute Value and Group

我基本上有一個帶有標題的表,我在C#中使用linq從數據庫中讀取。 在這些標題中,始終至少有一個始終相同; 總計和我希望它始終在右邊。

所以這里有一些我的數據如何布局:

Data
{
   Label,
   Value,
   Age  //Not used initially
}

樣本數據:

{"Dog", 7}
{"Cat", 3}
{"Other", 4}
{"Total", 14}

我想按此順序訂購標簽; 實際的動物名稱按其值按降序排序,Total附加到結尾:

"Dog", "Other", "Cat", "Total"

我如何在Linq中執行此操作。 如何根據另一個屬性的值訂購屬性?

一旦我有了標題的順序,是否有一種簡單的方法可以根據已經確定的順序訂購未來的行。 如果我想最初找到其中的標題(x => x.Age> 20),我如何根據與> 20集相同的順序對其中的標簽進行排序(x => x.Age <= 20)?

此查詢應該有效:

var query = from row in table
            let ignore = row.Label == "Total"
            orderby ignore, row.Value descending
            select row.Label;

//and corresponding lambda version
var lquery = table.OrderBy(row => row.Label == "Total")
                  .ThenByDescending(row => row.Value)
                  .Select(row => row.Label);

注意:創建一個ignore變量並不是完全必要的,它可以直接放在orderby子句中。 這樣,它使它更具可讀性。

在第二個問題中不確定你在問什么。


編輯:
在回應你的評論時,這將取決於你希望排序如何工作,至少寫得這樣。 如果表中只有一行要完全忽略,則此方法很有效。 如果你不止一個,那就不那么重要了。 問題是在“被忽略”的行中,也將按原始排序(在本例中為Value )進行排序。 添加另一行的簡單方法是添加到ignore條件。

var query = from row in table
            let ignore = row.Label == "Total" || row.Label == "Cost"
            orderby ignore, row.Value descending
            select row.Label;

要在“忽略”行中進行特定排序,需要更復雜的查詢:

var query = from row in table
            let ignore = row.Label == "Total" || row.Label == "Cost"
            let ignoreorder = row.Label == "Cost" ? 1 : 0
            orderby ignore, ignoreorder, row.Value descending
            select row.Label;

//and corresponding lambda version
var lquery = table.OrderBy(row => row.Label == "Total" || row.Label == "Cost")
                  .ThenBy(row => row.Label == "Cost" ? 1 : 0)
                  .ThenByDescending(row => row.Value)
                  .Select(row => row.Label);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM