Sort List <int>
Using C #, what is the best way to sort a list numerically? my list contains items 5,7,3 and I would like them to sort 3,5,7. I know a few longer ways, but would I suggest linq has a faster way?
it’s a pity that it was the end of the day, my mind, where he worked, didn’t see him change for the first time :(
+42
Spooks Sep 17 '10 at 20:08 2010-09-17 20:08
source share6 answers
There is no need for LINQ, just call Sort:
list.Sort(); Code example:
List<int> list = new List<int> { 5, 7, 3 }; list.Sort(); foreach (int x in list) { Console.WriteLine(x); } Result:
3 5 7 +103
Mark Byers Sep 17 '10 at 20:08 2010-09-17 20:08
source shareKeeping simplicity is the key.
Try below.
var values = new int[5,7,3]; values = values.OrderBy(p => p).ToList(); +27
Khizer Jalal Oct 26 2018-12-12T00: 00Z
source share var values = new int[] {5,7,3}; var sortedValues = values.OrderBy(v => v).ToList(); // result 3,5,7 +14
Will 17 Sep '10 at 20:12 2010-09-17 20:12
source share List<int> list = new List<int> { 5, 7, 3 }; list.Sort((x,y)=> y.CompareTo(x)); list.ForEach(action => { Console.Write(action + " "); }); +7
siva Apr 3 '13 at 11:32 2013-04-03 11:32
source shareSort integer list
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); } } } +4
Academy of Programmer Dec 13 '11 at 12:44 2011-12-13 12:44
source share 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(); 0
Jerry Feb 22 '17 at 22:36 2017-02-22 22:36
source share