0

I have an ArrayList that contains multiple String[] (String arrays).

Each String[] contains a key: name

What I want to do is sort the ArrayList based on the value of name.

Using Array.Sort did not work because it cannot compare String[]. How can I sort the ArrayList based on the value of name that is within the String[]?

9
  • 3
    Why ArrayList? I have never seen a scenario where List<T> didn't serve the purpose. Commented Apr 19, 2012 at 12:10
  • Is the key the first element in each of the Array[]'s? If so, you could always use LINQ. Commented Apr 19, 2012 at 12:12
  • Yes it's always the first element, but not the only one. Commented Apr 19, 2012 at 12:12
  • Why does it matter whether I use ArrayList or List? The sorting problem still exists no? Commented Apr 19, 2012 at 12:14
  • Yes, but it is simpler with List. Commented Apr 19, 2012 at 12:15

6 Answers 6

4

In LINQ:

var ordered = arrayList.Cast<String[]>().OrderBy(ar => arr[0]);

Normally it's better to use a strong typed List<String[]> instead of an ArrayList. When you say key it sounds as if you want to have a list of strings for each unique key. Then a Dictionary<String, String[]> would be the best choice.

Sign up to request clarification or add additional context in comments.

8 Comments

ArrayList doesn't implement IEnumerable<T>. You need arrayList.Cast<string[]>.OrderBy(arr => arr[0]);
Sure, 1 minute. Am I supposed to refresh the page every 10 seconds? :)
What does ar represent in this example? the string[] within the list?
@Pieter888: Sorry, that was a typo :( Corrected. It's the String[]
You still have a typo ar(r) => arr[0]
|
1

You should be using a List<string[]>. It supports everything that ArrayList does, and it is strongly typed.

Using a List<string[]>:

IEnumerable<string[]> sorted = myList.OrderBy(s => s[0]);

Comments

0

Try this

ArrayList arr = new ArrayList();
arr.ToArray().OrderBy(p => p);

1 Comment

I think you may mean p => p[0]?
0

Use Array.Sort(Array,IComparer) and write your own Comparer that looks for your key in your String[] and compare them.

Comments

0

You can create an IComparer an use

public virtual void Sort(
    IComparer comparer
)

http://msdn.microsoft.com/en-us/library/0e743hdt.aspx

Comments

0

You can pass to Array.Sort either a delegate or a class implementing an interface that implements the custom comparison you need. See some examples http://bytes.com/topic/c-sharp/answers/235679-two-dimension-array-sort.

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.