我有一个字符串数组
string[] my_array = {"5:five", "8:eight","4:four", "7:seven","1:one", "6:six"};
我希望有一个如下所示的输出字符串,以使值以升序连接
output_string = "onefourfivesixseveneight";
这是我的代码
string [] args = {"5:five", "8:eight","4:four", "7:seven","1:one",
"6:six" ,"840"};
string outputString = "";
int lowest_divisor = 1;
int dividend = Convert.ToInt32(args[args.Length - 1]);
for(int i = 0; i<args.Length - 1; i++)
{
string[] pairs = args[i].Split(":");
int divisor = Convert.ToInt32(pairs[0]);
string pairString = pairs[1];
if(i == 0)
{
lowest_divisor = divisor;
outputString = pairString;
}
else if(divisor <= lowest_divisor)
{
outputString = pairString + outputString;
lowest_divisor = divisor;
}
else if(divisor > lowest_divisor)
{
outputString = outputString + pairString;
}
}
答案 0 :(得分:4)
首先,我们只能将字符串限制为int:value格式
IEnumerable<string> validStrings = my_array.Where(x => x.Contains(':') && int.TryParse(x.Split(':')[0], out int test));
然后我们得到按整数值排序的列表
IEnumerable<string> orderedStrings = validStrings.OrderBy(x => int.Parse(x.Split(':')[0]));
然后我们可以将它们组合
string combined = string.Join("", orderedStrings.Select(x => x.Split(':')[1]));
答案 1 :(得分:3)
我认为最简单的方法是使用linq。 像这样:
string outputString = string.Join("", args.OrderBy(x => int.Parse(x.Split(':')[0])).Select(x => x.Split(':').Length > 1 ? x.Split(':')[1] : ""));
如果您不控制内容,则可以添加检查以确保其不会引发异常
答案 2 :(得分:3)
与提供的linq解决方案相比,这有点冗长。
SortedDictionary<int, string> dict = new SortedDictionary<int, string>();
foreach (string s in my_array)
{
string[] splitArr=s.Split(':');
dict.Add(Convert.ToInt32(splitArr[0]), splitArr[1]);
}
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<int, string> kvp in dict)
{
sb.Append(kvp.Value);
}
string final=sb.ToString();