如何按C#中的字符串长度对字符串数组进行排序 [英] How Do I Sort String Array By Length Of Strings In C#
本文介绍了如何按C#中的字符串长度对字符串数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Name
{
class LCS
{
int n;
static void Main()
{
LCS obj = new LCS();
obj.arrays();
Console.ReadLine();
}
public void arrays()
{
Console.WriteLine("Enter how many strings you want to enter:-");
n = Int32.Parse(Console.ReadLine());
List<string> sampleList = new List<string>();
Console.WriteLine("Enter " + n + " strings");
for (int i = 0; i < n; i++)
{
sampleList.Add(Console.ReadLine());
}
}
}
推荐答案
您可以使用LINQ:
You can use LINQ for that:
sampleList = sampleList.OrderBy(s => s.Length).ToList();
https:// msdn.microsoft.com/en-us/library/vstudio/bb534966%28v=vs.100%29.aspx [ ^ ]
就像我说的有几个这样做的方法。当然,ProgramFOX的LINQ解决方案是正确的。所以这是使用 List.Sort方法 [ ^ ]:
Like I said there are several ways to do this. And of course ProgramFOX's solution with LINQ is correct. So here is an alternative using List.Sort method[^]:
sampleList.Sort((x,y) => x.Length - y.Length);
好处是您没有创建List的新实例。
The benefit is you are not creating a new instance of List.
这篇关于如何按C#中的字符串长度对字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文