C#:如何根据字符串列表对对象列表进行排序

Tho*_*eld 9 c# linq sorting collections lambda

我有两个列表

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

List<Test> l_lstStudents = new List<Test> 
                            { new Test { Age = 20, Name = "A0" }, 
                              new Test { Age = 21, Name = "A1" }, 
                              new Test { Age = 22, Name = "A2" }, 
                              new Test { Age = 23, Name = "A3" }, 
                              new Test { Age = 24, Name = "A4" }, 
                            };
Run Code Online (Sandbox Code Playgroud)

Test班级在哪里

 public class Test
    {
        public String Name;
        public Int32 Age;
    }
Run Code Online (Sandbox Code Playgroud)

我需要l_lstStudents根据基于的方式对项目进行排序l_lstNames.所以排序列表就像,

List<Test> l_lstStudents = new List<Test> 
                        {  new Test { Age = 21, Name = "A1" }, 
                           new Test { Age = 23, Name = "A3" }, 
                           new Test { Age = 22, Name = "A2" }, 
                           new Test { Age = 24, Name = "A4" }, 
                           new Test { Age = 20, Name = "A0" }, 
                        };
Run Code Online (Sandbox Code Playgroud)

现在我正在使用for这个.

喜欢

  1. 创建一个新的Test对象列表.

  2. 迭代循环l_lstNamesTest从中获取对象l_lstStudent并将其添加到新创建的列表中.最后将新列表分配给l_lstStudent

请帮我以简单的方式做到这一点(Linq或Lambda)

Bot*_*000 9

试试这个:

l_lstStudents = l_lstStudents.OrderBy(s => l_lstNames.IndexOf(s.Name)).ToList()
Run Code Online (Sandbox Code Playgroud)

我认为这很清楚地表达了意图.