使用C#以数字方式对List进行排序的最佳方法是什么?我的清单有第5,7,3项,我希望它们排序3,5,7.我知道一些更长的方法,但我会想象linq有更快的方法吗?
对不起,这是一天的结束,我的想法是它工作的地方,没有看到它第一次改变:(
Mar*_*ers 141
这里不需要LINQ,只需调用Sort:
list.Sort();
Run Code Online (Sandbox Code Playgroud)
示例代码:
List<int> list = new List<int> { 5, 7, 3 };
list.Sort();
foreach (int x in list)
{
Console.WriteLine(x);
}
Run Code Online (Sandbox Code Playgroud)
结果:
3
5
7
Run Code Online (Sandbox Code Playgroud)
小智 35
保持简单是关键.
试试下面.
var values = new int[5,7,3];
values = values.OrderBy(p => p).ToList();
Run Code Online (Sandbox Code Playgroud)
Wil*_*ill 16
var values = new int[] {5,7,3};
var sortedValues = values.OrderBy(v => v).ToList(); // result 3,5,7
Run Code Online (Sandbox Code Playgroud)
小智 11
List<int> list = new List<int> { 5, 7, 3 };
list.Sort((x,y)=> y.CompareTo(x));
list.ForEach(action => { Console.Write(action + " "); });
Run Code Online (Sandbox Code Playgroud)
对降序的整数列表进行排序
class Program
{
private class SortIntDescending : IComparer<int>
{
int IComparer<int>.Compare(int a, int b) //implement Compare
{
if (a > b)
return -1; //normally greater than = 1
if (a < b)
return 1; // normally smaller than = -1
else
return 0; // equal
}
}
static List<int> intlist = new List<int>(); // make a list
static void Main(string[] args)
{
intlist.Add(5); //fill the list with 5 ints
intlist.Add(3);
intlist.Add(5);
intlist.Add(15);
intlist.Add(7);
Console.WriteLine("Unsorted list :");
Printlist(intlist);
Console.WriteLine();
// intlist.Sort(); uses the default Comparer, which is ascending
intlist.Sort(new SortIntDescending()); //sort descending
Console.WriteLine("Sorted descending list :");
Printlist(intlist);
Console.ReadKey(); //wait for keydown
}
static void Printlist(List<int> L)
{
foreach (int i in L) //print on the console
{
Console.WriteLine(i);
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
对 int 降序排序列表,您可以先排序然后反向
class Program
{
static void Main(string[] args)
{
List<int> myList = new List<int>();
myList.Add(38);
myList.Add(34);
myList.Add(35);
myList.Add(36);
myList.Add(37);
myList.Sort();
myList.Reverse();
myList.ForEach(Console.WriteLine);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150073 次 |
| 最近记录: |