1 April 2020

Sort numbers based on last digit in c#


Code:

using System; using System.Collections.Generic; using System.Linq; namespace Sort_numbers_based_on_last_digit { class Program { static void Main(string[] args) { List<MyNumbers> listMyNumbers = new List<MyNumbers>(); listMyNumbers.Add(new MyNumbers { Number = 13 }); listMyNumbers.Add(new MyNumbers { Number = 23 }); listMyNumbers.Add(new MyNumbers { Number = 123 }); listMyNumbers.Add(new MyNumbers { Number = 4 }); listMyNumbers.Add(new MyNumbers { Number = 345 }); listMyNumbers.Add(new MyNumbers { Number = 1235 }); listMyNumbers.Add(new MyNumbers { Number = 2345 }); listMyNumbers.Add(new MyNumbers { Number = 12345 }); listMyNumbers.Add(new MyNumbers { Number = 1 }); listMyNumbers.Add(new MyNumbers { Number = 2 }); listMyNumbers.Add(new MyNumbers { Number = 14 }); listMyNumbers.Add(new MyNumbers { Number = 24 }); listMyNumbers.Add(new MyNumbers { Number = 34 }); listMyNumbers.Add(new MyNumbers { Number = 124 }); listMyNumbers.Add(new MyNumbers { Number = 234 }); listMyNumbers.Add(new MyNumbers { Number = 1234 }); listMyNumbers.Add(new MyNumbers { Number = 5 }); listMyNumbers.Add(new MyNumbers { Number = 15 }); listMyNumbers.Add(new MyNumbers { Number = 25 }); listMyNumbers.Add(new MyNumbers { Number = 35 }); listMyNumbers.Add(new MyNumbers { Number = 45 }); listMyNumbers.Add(new MyNumbers { Number = 125 }); listMyNumbers.Add(new MyNumbers { Number = 12 }); listMyNumbers.Add(new MyNumbers { Number = 3 }); listMyNumbers.Add(new MyNumbers { Number = 235 }); List<MyNumbers> listMyNumbers1 = new List<MyNumbers>(); foreach (var a in listMyNumbers) { MyNumbers obj = new MyNumbers(); obj.Number = a.Number; obj.LastNumber= Math.Abs(a.Number) % 10; obj.TotalCount = (a.Number).ToString().Length; listMyNumbers1.Add(obj); } List<MyNumbers> listMyNumbers2 = listMyNumbers1.OrderBy(x => x.LastNumber).ThenBy(x=>x.TotalCount).ToList(); Console.WriteLine("Input:"); foreach(var a in listMyNumbers) { Console.WriteLine(a.Number); } Console.WriteLine("Output:"); foreach (var a in listMyNumbers2) { Console.WriteLine(a.Number); } Console.ReadLine(); } } public class MyNumbers { public int Number { get; set; } public int LastNumber { get; set; } public int TotalCount { get; set; } } }


Input:

Output:


No comments:

Post a Comment