C# : How to sort a list of object based on a list of string

标签 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" }, 
                            };

Test 是类

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

我需要根据 l_lstNamesl_lstStudents 中的项目进行排序。所以排序后的列表就像,

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" }, 
                        };

现在我正在使用 for 来执行此操作。

喜欢

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

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

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

最佳答案

试试这个:

l_lstStudents = l_lstStudents.OrderBy(s => l_lstNames.IndexOf(s.Name)).ToList()

我认为这表达了非常明确的意图。

关于C# : How to sort a list of object based on a list of string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9633426/

相关文章:

c# - 如何为类中的值类型变量分配内存

c# - 检查 List<T> 中是否存在以下项目

c# - Linq:将数据选择到多个列表中

javascript - 在 JavaScript : Shouldn't returning a boolean be enough for a comparison function? 中排序

将在过去 k 天内维护前 n 个项目的算法?

c# - 排序字符串数字

c# - 即使类被多次调用,如何使构造函数只被调用一次?

c# - 我的通用类型转换器味道不好,运行时异常,对象包罗万象,拳击等

c# - 不知道为什么使用 headless (headless)浏览器

c# - "dot notation"中的 LINQ to Entities 查询