按用户分数对列表框项目排序

时间:2014-02-04 14:48:33

标签: c# winforms sorting

我希望向顶级用户显示存储在列表框中的得分,如下所示:

user1:95
user3:80
user2:90
user4:120

输出必须是:

user4 score: 120
user1 score: 95
user2 score: 90
user3 score: 80

我目前的代码是:

    string[,] users = new string[listBox1.Items.Count, 2];
    int[] scores = new int[listBox1.Items.Count];
    for (int i = 0; i < listBox1.Items.Count; i++)
    {
        string[] s = listBox1.Items[i].ToString().Split(':');
        users[i, 0] = s[1];
        users[i, 1] = s[0];
        scores[i] = int.Parse(users[i, 0]);
    }
    Array.Sort(scores);
    Array.Reverse(scores);
    for (int i = 0; i < 4; i++)
    {
        Console.WriteLine(users[i, 1] + " score: " + scores[i]);
    }

输出:

user1 score: 120
user3 score: 95
user2 score: 90
user4 score: 80

用户名不正确。 感谢。

2 个答案:

答案 0 :(得分:1)

WinForms解决方案:将项目复制到数组,对数组进行排序,然后打印数组:

string [] items = new string[listBox1.Items.Count];
listBox1.Items.CopyTo(items, 0);
Array.Sort(items, delegate(string a, string b) {
    // Should add error checking here in case string in wrong format
    int ascore = Int32.Parse(a.Substring(a.IndexOf(':') + 1));
    int bscore = Int32.Parse(b.Substring(b.IndexOf(':') + 1));
    return ascore == bscore ? 0 : (ascore < bscore ? 1 : -1);
});
foreach(string s in items) {
    Console.WriteLine(s.Replace(":", " score: "));
}

编辑:通过在第6行更改a到b来解决问题。

答案 1 :(得分:0)

转换为List,然后按:

使用LINQ的顺序
// order
List<UserScore> scores = new List<UserScore>(listBox.Items.Cast<UserScore>());
var orderedScores = scores.OrderBy(li => li.Score).ToList<UserScore>();

// re-populate the ListBox
listBox.Items.Clear();
listBox.Items.AddRange(orderedScores.ToArray<UserScore>());


public class UserScore
{
    public string UserName { get; set; }
    public int Score { get; set; }
}

这比使用ListBox.Sort()

更简单
相关问题