gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:39:27 25 4
gpt4 key购买 nike

我有两个类似的列表

 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com