大家好,我的问题是当我在c#中添加数据到字典时,我想切换(Sortype)字符串来检查用户想要的订单数据这样的:
string SortType="ByDownloads";
Dictionary<string, Data> WorldInfo = JsonConvert.DeserializeObject<Dictionary<string, Data>>(Res.Body.ToString());
switch (SortType)
{
case "ByDownloads":
WorldInfo.OrderByDescending(AllData => AllData.Value.PostDownloads).ToList();
break;
case "ByViews":
WorldInfo.OrderBy(AllData => AllData.Value.PostViews).ToList();
break;
}
以这种方式,代码将不工作,数据不排序但是当我使用这种方式代码将工作:
Dictionary<string, Data> WorldInfo = JsonConvert.DeserializeObject<Dictionary<string, Data>>(Res.Body.ToString());
var NewSortedDictionary = WorldInfo.OrderByDescending(AllData => AllData.Value.PostViews).ToList();
所以我正在寻找正确的方法来做到这一点,并使用(WorldInfo)字典和开关(SortType),然后我使用它而不是(NewSortedDictionary)。谢谢你:)
感谢所有评论这个问题的人:)我用这种方式修复了它,我希望它将来能帮助别人:
SortType="ByDownloads";
Dictionary<string, Data> NormallDictionary = JsonConvert.DeserializeObject<Dictionary<string, Data>>(Res.Body.ToString());
List<KeyValuePair<string,Data>> MySortedDictionary= new List<KeyValuePair<string, Data>>();
switch (SortType)
{
case "ByDownloads":
MySortedDictionary = NormallDictionary.OrderByDescending(x => x.Value.Downloads).ToList();
break;
case "ByViews":
MySortedDictionary = NormallDictionary.OrderByDescending(x => x.Value.Views).ToList();
break;
}
现在你可以使用MySortedDictionary
它在您的情况下不起作用的原因是orderbydescent在排序后返回一个对象。
你可以这样做
Dictionary<string, Data> MyDictionary = JsonConvert.DeserializeObject<Dictionary<string, Data>>(Res.Body.ToString()));
var data = Sortype == "ByViews" ? WorldInfo.OrderByDescending(AllData => AllData.Value.WorldPDownloads).ToList() : Sortype == 'ByDownloads' ? WorldInfo.OrderBy(AllData => AllData.Value.WorldPDownloads).ToList() : null;
或
string Sortype = "ByDate";
Dictionary<string, Data> MyDictionary = JsonConvert.DeserializeObject<Dictionary<string, Data>>(Res.Body.ToString());
switch (Sortype)
{
case "ByViews":
WorldInfo = WorldInfo.OrderByDescending(AllData => AllData.Value.WorldPDownloads).ToList();
break;
case "ByDownloads":
WorldInfo =WorldInfo.OrderBy(AllData => AllData.Value.WorldPDownloads).ToList();
break;
}
我不知道这是否是一个错误或只是故意错过,但您正在设置string Sortype ="ByDate";
而实际上在switch
语句中没有"ByDate"
。