[英]Sort List in Descending Order via Array Count
我正在嘗試按每條記錄中持有的贊成票數量對從數據庫中獲得的數據列表進行降序排序。 這是我目前擁有但不起作用的。 注意:upvotes 字段是 model class 中的 string[] 數組。
//Method to get all popular posts and display them in a list
public async void GetPostInfo()
{
PostsMod = new ObservableCollection<IPosts>();
var temp = await _postsProxy.GetAllPosts();
if (temp != null)
{
if (temp.Count > 0)
{
var orderedList = temp.OrderByDescending(x => x.UpVoteId.Count()).ToList(); //Orders the records in descending order based on how many upvotes they contain, puts it into a new list
foreach (var item in orderedList)
{
PostsMod.Add(item);
}
}
else
PostsMod.Add(temp[0]);
}
}
所有帖子都放入 var temp 中,然后臨時列表應該通過計數的贊成票數量按降序排列。請記住,贊成票字段再次是 model class 中的字符串 [] 數組。
它出現一條錯誤消息:System.ArgumentNullException:'Value cannot be null。 參數名稱:source'
編輯:對不起,這是我的錯誤,我犯了 model class 中的字段不匹配的愚蠢錯誤。 因此導致我的贊成票是 null。
System.ArgumentNullException: 'Value cannot be null. Parameter name: source'
System.ArgumentNullException: 'Value cannot be null. Parameter name: source'
來自 null IEnumerable <T>
傳遞給 Linq 擴展方法,您的代碼中唯一的一個是Count 。
嘗試這個:
var orderedList = temp.OrderByDescending(x => x.UpVoteId?.Count()).ToList();
這將失敗,因為temp.Count
將為 0:
else
PostsMod.Add(temp[0]);
話雖如此,盡管不是問題的一部分,但您不應在此處返回 null。 您應該始終獲取一個集合,無論是否為空,或者拋出異常而不是吞下它。
if (temp != null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.