Is there a .NET build-in method that would solve my scenario?
{ "Mark", "Tom", "Mat", "Mary", "Peter" }
"Ma"
as sorting string helper{ "Mark", "Mary", "Mat", "Tom", "Peter" }
I know that function solving this would be easy, but I'am interested is such method exists.
PS. Using .NET 4.0
Using .Net 3.5 (and above) the OrderByDescending and ThenBy methods in Linq will be able to do what you want. eg:
var ordered = strings.OrderByDescending(s => s.StartsWith("Ma")).ThenBy(s => s);
I think that method does not exist.
I solved 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 elements with your 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With