VB.net sort and retain keys
I have a situation where I need to sort arrays and preserve the current key - value pairs.
For example, this array:
(0) = 4
(1) = 3
(2) = 1
(3) = 2
Needs to sort like this
(2) = 1
(3) = 2
(1) = 3
(0) = 4
Retaining the original keys. Array.Sort(myArray) sorts into the right sequence but doesn't keep the indexes. I need a variant that开发者_如何学C does.
edit Using the links, this seems close to what I want. Do I just need to remove the extra brackets to convert this to vb.net?
myList.Sort((firstPair,nextPair) =>
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
(also would I intergrate this as a function or something else?)
In an array, the order is determined by the indexes (what you call "keys"). Thus, there cannot be an array like this:
(2) = 1
(3) = 2
(1) = 3
(0) = 4
What you need is a data structure that has keys, values and an order (which is independent from the keys). You can use a List(Of KeyValuePair)
or (if you use .net 4) List(Of Tuple(Of Integer, Integer))
for this; a few examples are shown in the link provided by Ken in the comment (which I will repeat here for convenience):
- How do you sort a C# dictionary by value?
EDIT: Another option would be to use LINQ to automatically create a sorted IEnumerable(Of Tuple(Of Integer, Integer))
:
Dim a() As Integer = {4, 3, 1, 2} ' This is your array
Dim tuples = a.Select(Function(value, key) New Tuple(Of Integer, Integer)(key, value))
Dim sorted = tuples.OrderBy(Function(t) t.Item2)
(untested, don't have Visual Studio available right now)
Since you are using .net 2.0 (since you said that you are using Visual Studio 2005 in one of the comments), using an OrderedDictionary might be an option for you, if every array value appears only once. Since OrderedDictionaries are ordered by the key, you could add your array entries to such a dictionary, using
- the array index as the dictionary value and
- the array value as the dictionary key (which will be used to order the dictionary).
What you are looking for is storing it as a Dictionary < int,int > and sort by the dictionary by Value.
I think the VB .Net synatx for dictionary is Dictionary( of Int, Int)
精彩评论