Was ist der beste Weg, eine Liste numerisch zu sortieren? Meine Liste enthält Elemente 5,7,3 und ich möchte, dass sie 3,5,7 sortiert wird. Ich kenne einige längere Wege, aber ich würde mir vorstellen, dass Linq einen schnelleren Weg hat?
entschuldigung, es war Ende des Tages, meine Gedanken sind wo anders, als es funktionierte. Ich habe es nicht beim ersten Mal gesehen :(
LINQ ist hier nicht erforderlich, rufen Sie einfach Sort an:
list.Sort();
Beispielcode:
List<int> list = new List<int> { 5, 7, 3 };
list.Sort();
foreach (int x in list)
{
Console.WriteLine(x);
}
Ergebnis:
3
5
7
Einfach zu halten ist der Schlüssel.
Versuchen Sie unten.
var values = new int[5,7,3];
values = values.OrderBy(p => p).ToList();
var values = new int[] {5,7,3};
var sortedValues = values.OrderBy(v => v).ToList(); // result 3,5,7
List<int> list = new List<int> { 5, 7, 3 };
list.Sort((x,y)=> y.CompareTo(x));
list.ForEach(action => { Console.Write(action + " "); });
Sortieren Sie eine Liste von Ganzzahlen absteigend
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);
}
}
}
Sortiere die Liste der int absteigend. Du kannst sie zuerst sortieren und umkehren
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);
}
}
double jhon = 3;
double[] numbers = new double[3];
for (int i = 0; i < 3; i++)
{
numbers[i] = double.Parse(Console.ReadLine());
}
Console.WriteLine("\n");
Array.Sort(numbers);
for (int i = 0; i < 3; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();