我遇到了这个问题,我需要根据其他列表进行降序排序。 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" };
找到几个相同的样本,但不匹配我正在寻找的。谢谢你的帮助。
答案 0 :(得分:3)
使用Dictionary<string, int>
到Name
映射创建Age
并在订购方式中使用它:
var dict = students.ToDictionary(x => x.Name, x => x.Age);
var ordered = source.OrderByDescending(x => dict[x.Name]).ToList();
或者您只需订购students
集合,然后只选择Name
:
var ordered = students.OrderByDescending(x => x.Age)
.Select(x => x.Name)
.ToList();
答案 1 :(得分:3)
如果您只想按顺序降序:
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!
答案 2 :(得分:1)
我认为这就是你要找的东西
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();
OR
List<String> l_lstNames2 = l_lstStudents.OrderByDescending(a => a.Age)
.Where(a => l_lstNames.Any(b => b == a.Name))
.Select(a => a.Name).ToList();