Dictionary是无序的,如果想排序,需要使用SortDictionary.下面是一个用法示例
//按照某个字段排序 public List<Card> SortByCardItem(List<Card> cards,string itemName,SortOrder sortOrder) { List<Card> returnList = new List<Card>(); SortedDictionary<string, Card> sd = new SortedDictionary<string, Card>(); for (int i = 0; i < cards.Count; i++) { var v = cards[i].CardItems.Find(c => c.Name.Equals(itemName)); if(v==null)//说明不存在某个字段 { return cards; } sd.Add(v.Value, cards[i]); } if (sortOrder==SortOrder.Ascending)//升序 { foreach (var item in sd) { returnList.Add(item.Value); } } else//降序 { foreach (var item in sd.Reverse()) { returnList.Add(item.Value); } } return returnList; }