6

Is there a .NET build-in method that would solve my scenario?

  1. Got an array of strings ex. { "Mark", "Tom", "Mat", "Mary", "Peter" }
  2. I use string "Ma" as sorting string helper
  3. My array result is { "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

3
  • The strings that have the matching index that needs to be sorted. What about the other strings, that do not have the matching string? If you want, you can filter out all the matching string and sort them and finally append the list with remaining elements. Commented Nov 16, 2011 at 15:30
  • What's the benefit of sorting elements that match only the specified prefix while leaving the other elements in their original relative ordering? Do the sorted elements always end up at the beginning? Commented Nov 16, 2011 at 15:31
  • Homework, if so please tag it. Commented Nov 16, 2011 at 15:32

2 Answers 2

17

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This one's linq-fu is strong. +1
1

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.