【问题标题】:Descending sorting of a list of object based on a count from a different class根据来自不同类的计数对对象列表进行降序排序
【发布时间】:2014-02-12 03:37:47
【问题描述】:

我被困在这个问题上,我需要根据其他列表进行降序排序。 l_lstNames 需要按年龄降序更新。

public class Test
{
    public String Name;
    public Int32 Age;
}

List<String> l_lstNames = new List<String> { "A1", "A3", "A2", "A4", "A0" };

List<Test> l_lstStudents = new List<Test> 
{ 
    new Test { Age = 33, Name = "A0" }, 
    new Test { Age = 10, Name = "A1" }, 
    new Test { Age = 50, Name = "A2" }, 
    new Test { Age = 8,  Name = "A3" }, 
    new Test { Age = 25, Name = "A4" }, 
};

// Output
List<String> l_lstNames = new List<String> { "A2", "A0", "A4", "A1", "A3" };

找到几个相同的样本,但与我正在寻找的不匹配。谢谢你的帮助。

【问题讨论】:

标签: c# .net linq sorting lambda


【解决方案1】:

使用NameAge 的映射创建Dictionary&lt;string, int&gt;,并在order 方法中使用它:

var dict = students.ToDictionary(x => x.Name, x => x.Age);

var ordered = source.OrderByDescending(x => dict[x.Name]).ToList();

或者您可以只订购students 收藏然后选择Name only:

var ordered = students.OrderByDescending(x => x.Age)
                      .Select(x => x.Name)
                      .ToList();

【讨论】:

  • 完美!事实上,我的学生名单在 dict 中,只需要您的一行代码即可获得解决方案!谢谢。
【解决方案2】:

如果您只想按降序排列名称:

var sorted = l_lstStudents           // From the list of students
    .OrderByDescending(l => l.Age)   // with the oldest student first
    .Select(s => s.Name)             // give me just the names
    .ToList();                       // in a list!

【讨论】:

    【解决方案3】:

    我想这就是你要找的东西

    List<String> l_lstNames1 = (from student in l_lstStudents
                              where l_lstNames.Any(a => student.Name == a)
                              orderby student.Age descending
                              select student.Name ).ToList();
    

    List<String> l_lstNames2 = l_lstStudents.OrderByDescending(a => a.Age)
                                    .Where(a => l_lstNames.Any(b => b == a.Name))
                                    .Select(a => a.Name).ToList();
    

    【讨论】:

    • 谢谢。这也帮助了我。
    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2020-05-14
    • 2023-04-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多