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[]
?
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.
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]);
Try this
ArrayList arr = new ArrayList();
arr.ToArray().OrderBy(p => p);
使用Array.Sort(Array,IComparer)并编写自己的比较器,该比较器在String []中查找您的键并进行比较。
You can create an IComparer
an use
public virtual void Sort(
IComparer comparer
)
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.