Reputation: 37
I have 2 arrays that i want that i want to sort, but keep the the elements aligned correctly. for instance button1 at element[x] stays with textbox1 at element[x]. theres probably another structure i could use but i can't figure it out.
String[] Teams = {
textBox1.Text, textBox2.Text, textBox3.Text,
textBox4.Text, textBox5.Text, textBox6.Text,
textBox7.Text, textBox8.Text, textBox9.Text
};
int[] Scores = {
Convert.ToInt32(button1.Text), Convert.ToInt32(button2.Text), Convert.ToInt32(button3.Text),
Convert.ToInt32(button4.Text), Convert.ToInt32(button5.Text), Convert.ToInt32(button6.Text),
Convert.ToInt32(button7.Text), Convert.ToInt32(button8.Text), Convert.ToInt32(button9.Text)
};
Upvotes: 0
Views: 112
Reputation: 567
With Linq:
var sortedByTeam = Teams
.Zip(Scores, (t, s) => new { Team = t, Score = s })
.OrderBy(x => x.Team).ToList();
Upvotes: 0
Reputation: 1365
Hope the codes below help you. Please let me know if it is working as per your intention. Thanks
String[] Teams = {
"TeamC", "TeamB", "TeamA"
};
int[] Scores = {
0, 1, 2
};
var sortedTest = Teams
.Select((x, i) => new KeyValuePair<string, int>(x.ToString(), i))
.OrderBy(x => x.Key)
.ToList();
String[] TeamsSorted = sortedTest.Select(x => x.Key).ToArray();
List<int> idx = sortedTest.Select(x => x.Value).ToList();
List<int> sortedScores = new List<int>();
for (int i = 0; i < idx.Count; i++)
{
sortedScores.Add(Scores[idx[i]]);
}
Console.WriteLine("Sorted Teams: ");
TeamsSorted.ToList().ForEach((m) => Console.WriteLine(m));
Console.WriteLine("Sorted Scores: ");
sortedScores.ToList().ForEach((m) => Console.WriteLine(m));
Upvotes: 0
Reputation: 13655
The first way that comes to mind is to create a data structure for the pairs of data, put those into an array then sort that array by the desired data. You didn't actually specify which data you are wanting to sort on so I will assume it's the textBoxN.Text
values.
struct DataInfo {
public string Name,
public string Value
}
var data = new List<DataInfo>();
for(var x = 1; x < 10; x++) {
var textBox = this.Find("textBox" + x);
var button = this.Find("button" + x); // find the controls somehow
data.Add(new DataInfo { Name = Convert.ToInt32(button.Text), Value = textBox.Text };
}
data.Sort((left, right) => left.Value.CompareTo(right.Value));
There are actually a couple of ways to sort but the easiest is to pass a lambda into the Sort method on List and just do your sort logic right in there.
I hope this helps, good luck.
Upvotes: 1