我的資料在sql中是按這個順序排列的。
現在,我想用QuestionDataTypeId和DisplayOrder對這個串列進行排序,但希望這個QuestionDataTypeId=0在最后。所以最后的結果將是第一行=6然后7然后8,然后1到5。
我想用C#和linq來實作這個目標。
到目前為止,我嘗試了什么?
這是我的代碼,但它不作業。
var data = entity
.OrderByDescending(m => m.QuestionDataTypeId == 0)
.ThenBy(m => m.QuestionDataTypeId)
.ThenBy(m => m.DisplayOrder)。
我已經解決了這個問題,合并了2個不同的變數,分別為QuestionDataTypeId = 0和所有其他的QuestionDataTypeId排序,但我只想知道在這種情況下,單行的正確行數是什么。
如果有任何幫助,我將非常感激。
uj5u.com熱心網友回復:
你可以為OrderBy撰寫你自己的比較器
示例資料結構:public record Table
{
public Table(int qdtId, int displayOrder, string text)
{
QuestionDataTypeId = qdtId;
DisplayOrder = displayOrder;
文本 = 文本。
}
public int QuestionDataTypeId { get; set; }
public int DisplayOrder { get; set; }
public string Text { get; set; }
}
public class TableComparer : IComparer<Table>
{
public int Compare(Table? x, Table? y)
{
if(x.QuestionDataTypeId!= 0 && y.QuestionDataTypeId! =0 || x.QuestionDataTypeId == 0 && y.QuestionDataTypeId == 0)
{
return y.QuestionDataTypeId.CompareTo(x.QuestionDataTypeId)。
}
return x.QuestionDataTypeId == 0 && y.QuestionDataTypeId != 0 ? int.MinValue : int.MaxValue。
}
然后在代碼中:
List<StringConcatBug.Table> list = new( )
{
new(0, 1, "Comfortable") 。
new(0, 2,"attainable") 。
new(0, 3,"最近目標")。
new(0, 4,"舒服")。
new(2, 2,"Last Name") 。
new(3, 3,"Email") 。
new(0, 5, " feeling")。
new(1, 1, "First Name") 。
};
var ordered = list.OrderByDescending(t=>t,new TableComparer()>。)
foreach(var v in ordered){ Console.WriteLine(v);}
輸出
Table { QuestionDataTypeId = 1, DisplayOrder = 1, Text = First Name }
表 { QuestionDataTypeId = 2, DisplayOrder = 2, Text = Last Name }
表 { QuestionDataTypeId = 3, DisplayOrder = 3, Text = Email }
表 { QuestionDataTypeId = 0, DisplayOrder = 1, Text = Comfortable }
表 { QuestionDataTypeId = 0, DisplayOrder = 2, Text = attainable }
表 { QuestionDataTypeId = 0, DisplayOrder = 3, Text = recent goal }
表 { QuestionDataTypeId = 0, DisplayOrder = 4, Text = comfortable }
表 { QuestionDataTypeId = 0, DisplayOrder = 5, Text = feeling }
uj5u.com熱心網友回復:
我通常使用這種演算法
var mult=100000; //你可以根據的記錄數量選擇一個不同的數字。
//你期望的同一型別;數字不應重疊。
var data = entity
.OrderBy(m => (m.QuestionDataTypeId*mult m.DisplayOrder))
.....
uj5u.com熱心網友回復:
嘗試替換 QuestionDataTypeId where value = 0
.OrderBy(x=>x.QuestionDataTypeId==0? int.MaxValue:x.QuestionDataTypeId)
.ThenBy(t=>t.DisplayOrder)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310087.html
標籤:
上一篇:Linq查詢不能選擇欄位串列
下一篇:通過多個值進行Linq排序

