C # - sorting strings by another string as helper

Is there a .NET build method that resolves my script?

  • Got an array of ex strings. { "Mark", "Tom", "Mat", "Mary", "Peter" }
  • I use the string "Ma" as a sorting string helper
  • Array result { "Mark", "Mary", "Mat", "Tom", "Peter" }

I know that the function that solves this would be simple, but I am interested in such a method.

PS. Using .NET 4.0

+6
source share
2 answers

Using .Net 3.5 (and higher) OrderByDescending and ThenBy in Linq will be able to do what you want. eg:

 var ordered = strings.OrderByDescending(s => s.StartsWith("Ma")).ThenBy(s => s); 
+17
source

I think the method does not exist.
I decided with this:

 public static string[] Sort(this string[] list, string start) { List<string> l = new List<string>(); l.AddRange(list.Where(p => p.StartsWith(start)).OrderBy(p => p)); l.AddRange(list.Where(p => !p.StartsWith(start)).OrderBy(p => p)); return l.ToArray(); } 

So you can do

 string[] list = new string[] { "Mark", "Tom", "Mat", "Mary", "Peter" }; string[] ordered_list = list.Sort("Ma"); 

If you need to order items with your own string and leave others unsorted, use this:

 public static string[] Sort(this string[] list, string start) { List<string> l = new List<string>(); l.AddRange(list.Where(p => p.StartsWith(start)).OrderBy(p => p)); l.AddRange(list.Where(p => !p.StartsWith(start))); // l.AddRange(list.Where(p => !p.StartsWith(start)).OrderByDescending(p => p)); return l.ToArray(); } 
+1
source

Source: https://habr.com/ru/post/901626/


All Articles