好的,我希望通过属性(WordList)对List(UserList)进行排序,尽管我需要(WordList)首先按特定属性排序。
整个Sort UserList方法不会对UserList进行排序,无论我是尝试(userName)还是(WordList)。(wordName)或(WordList)。(amountOfGuesses)
public class User
{
public string userName;
public List<Word> wordList;
public User() { }
public User(string name, String word, int guesses)
{
this.userName = name;
wordList = new List<Word>();
Word theWord = new Word(word, guesses);
this.wordList.Add(theWord);
}
}
public List<User> SortUserList(String g)
{
String option = g.ToLowerInvariant();
switch(option){
case "name":
this.UserList.OrderBy(x=> x.userName);
break;
case "word":
this.UserList.OrderBy(k => k.wordList.OrderBy(w => w.wordName));
break;
case "guess":
this.UserList.OrderBy(m=> m.wordList.OrderBy(y => y.amountOfGuesses));
break;
}
return UserList;
}
public void Test()
{
User xor = new User("xor", "xadfs", 20);
User bob = new User("bob", "char", 3);
User james = new User("james", "adfsad", 200);
UserList.Add(bob);
UserList.Add(james);
UserList.Add(xor);
}
答案 0 :(得分:2)
如果您想按照第一个字(按时间顺序)对用户进行排序,则可以在Min
序列上使用OrderBy
代替内部wordList
。
您对代码的另一个问题是,您假设外部OrderBy
将更新源UserList
序列。它没有;相反,它保持源不变,并返回一个枚举有序序列的新查询。您可以通过调用ToList
并返回结果来填充此内容。
case "name":
return this.UserList.OrderBy(x => x.userName).ToList();
case "word":
return this.UserList.OrderBy(k => k.wordList.Min(w => w.wordName)).ToList();
case "guess":
return this.UserList.OrderBy(m => m.wordList.Min(y => y.amountOfGuesses)).ToList();
答案 1 :(得分:1)
如果您需要按列表的“top”元素排序,可以使用FirstOrDefault()
来提取它:
UserList.OrderBy(k => k.wordList.OrderBy(w => w.wordName).FirstOrDefault());
我认为这可以做你想要的,但我还不确定你究竟在问什么: - )