Store and sort list of people that have both a DateTime and Int value
Using C# in .Net 2.0
When someone joins my server, I want to add their name, and the DateTime that they joined开发者_JAVA百科 to a list/dictionary, as well as their score, which gets updated frequently.
I then want to be able to sort that list/dictionary by the DateTime or score, based on a boolean value, so that I can return the top 50% of the list/dictionary. i.e. return the names of the top 50% longest time between join and now, or the top 50% scores.
I've attempted it using two separate dictionaries, then using a custom sort by value method, but it's messy, and doesn't seem to work.
Is there an elegant way of doing this?
I think you can make the DateTime and score as a pair, and store it as key in your collection.
Then you can use Array.Sort to sort the keys collection and the Sort method can be passed a IComparer, which can be implemented according your requirements.
You could create a class to represent each user:
class User {
public string Name { get; set; }
public DateTime DateJoined { get; set; }
public int Score { get; set; }
}
Then if you have a list of users
List<User> users = new List<User>();
you could sort it by score:
users.Sort(delegate (string left, string right) {
return left.Score.CompareTo(right.Score);
});
or by date joined:
users.Sort(delegate (string left, string right) {
return left.DateJoined.CompareTo(right.DateJoined);
});
If you can use C# 3 or later then this gets a lot nicer with Linq and Lambda expressions.
For example:
var top50pcUsersByScore = users.OrderBy(u => u.Score).Take(users.Count / 2);
Create classes that implement ICompare(Of T)
. I realise you're writing in C#, but here's VB.NET code.
Public Class Main
Public Sub SortByLoginTime(accounts As IList(Of UserAccount))
Array.Sort(accounts, New UserAccountLoginTimeComparer)
End Sub
Public Sub SortByScore(accounts As IList(Of UserAccount))
Array.Sort(accounts, New UserAccountScoreComparer)
End Sub
End Class
Public Class UserAccount
Public Property LoginTime As Date
Public Property Score As Integer
End Class
Public Class UserAccountLoginTimeComparer
Implements IComparer(Of UserAccount)
Public Function Compare(x As UserAccount, y As UserAccount) As Integer Implements System.Collections.Generic.IComparer(Of UserAccount).Compare
Return Date.Compare(x.LoginTime, y.LoginTime)
End Function
End Class
Public Class UserAccountScoreComparer
Implements IComparer(Of UserAccount)
Public Function Compare(x As UserAccount, y As UserAccount) As Integer Implements System.Collections.Generic.IComparer(Of UserAccount).Compare
Return x.Score - y.Score
End Function
End Class
精彩评论