提问人:Damkulul 提问时间:8/29/2023 最后编辑:Damkulul 更新时间:8/29/2023 访问量:103
如何根据数字字符串对列表进行排序 [duplicate]
How to sort a list according to numeric strings [duplicate]
问:
我的列表包含具有 2 个字符串字段的对象:
public class worker
{
public string Name { get; set; }
public string Hours{ get; set; }
}
List<worker> work= new List<worker>();
work.Add(new worker{"Ron","2"});
work.Add(new worker{"Alex","202" });
work.Add(new worker{"Brad","11"});
work.Add(new worker{"Micky","33"});
work.Add(new worker{"Anna","22"});
排序后我需要此输出:澄清 - 小时数是小时数。
我该怎么做?Alex,Micky,Anna,Brad,Ron
答:
0赞
MrSpt
8/29/2023
#1
如果每个字符串肯定都是一个数字,则可以像这样进行排序。
var orderedWorkers = work.OrderByDescending(x => int.Parse(x.Hours));
如果您的字符串不是数字,我会在工作类中创建一个单独的属性,以确保始终返回一个有效的数字。
public class worker
{
public string Name { get; set; }
public string Hours{ get; set; }
public int HoursAsInt
{
get
{
int.TryParse(Hours, out int hoursAsInt);
return hoursAsInt;
}
}
}
1赞
abolfazl sadeghi
8/29/2023
#2
如果您确定所有小时都是数字,则必须使用该方法
var _List = string.Join("," ,
work.OrderByDescending(d => int.Parse(d.Hours)
).Select(d => d.Name).ToArray());
否则,您必须在类中创建一个字段或单独的类,如下所示
var _Lists = string.Join(",",
work.OrderByDescending(d => ConvertData.ConvertIntTostring(d.Hours)
).Select(d => d.Name).ToArray());
转换数据
public static class ConvertData
{
public static int ConvertIntTostring(string number)
{
int result = 0;
int.TryParse(number, out result);
return result;
}
}
评论