How to sort using .substring | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to sort using .substring

I want to sort street names alphabetically e.g Default: 43 Eagle Str 28 Snow Drv 61 Chain Ave Desired outcome 61 Chain Ave 43 Eagle Str 28 Snow Drv sort using the names not numbers

25th Aug 2018, 7:25 AM
Comfort Motebejane
Comfort Motebejane - avatar
3 Answers
+ 2
Currently learning a lot about LINQ, so I did find your question a nice challenge. This is my code. ordered_adress_list = address_list.OrderBy(j => j.Split(' ')[1]).ToList(); ordered_adress_list = address_list.OrderBy(j => j.Substring(3)).ToList(); address_list.Sort((a,b) => string.Compare(a.Substring(3),b.Substring(3))); https://code.sololearn.com/cVYvZtG605J1
25th Aug 2018, 10:14 PM
sneeze
sneeze - avatar
+ 4
Here's what I found from search, solution was incomplete, not designed to anticipate a case where street number digits was more than 2. using System; // Found here: // https://social.msdn.microsoft.com/Forums/en-US/9e5c15f9-ad29-4469-ae1c-83bc5ec494f4/sort-string-array-base-on-it-substring namespace SortArraySubstring { class Example { static void Main(string[] args) { string[] arr = new string[3] { "43 Eagle Str", "28 Snow Drv", "61 Chain Ave" }; // Old version compatibility /* Array.Sort(arr, delegate(string a, string b) { return string.Compare(a.Substring(3), b.Substring(3)); }); */ // Using lambda Array.Sort(arr, (a, b) => string.Compare(a.Substring(3), b.Substring(3))); foreach(string s in arr) { Console.WriteLine(s); } } } }
25th Aug 2018, 8:50 AM
Ipang
+ 2
thank you I'll try it out now!
25th Aug 2018, 9:10 AM
Comfort Motebejane
Comfort Motebejane - avatar