我有一个 List
,并且我有一个用 int[]
表示的新顺序,我想要将 List
中的项目按照 int[]
中的顺序重新排列。这是我实现的代码:
class Program
{
static void Main(string[] args)
{
List<Test> tests = new List<Test>() {
new Test(){ No = 201 },
new Test(){ No = 101 },
new Test(){ No = 300 },
new Test(){ No = 401 },
new Test(){ No = 500 },
new Test(){ No = 601 }
};
int[] newOrder = new int[6] { 201, 401, 300, 101, 601, 500 };
//after the opration the List should contain items in order 201, 401, 300, 101, 601, 500
List<Test> newTests = new List<Test>();
foreach(var order in newOrder)
{
var item = tests.SingleOrDefault(t => t.No == order);
if (item != null)
newTests.Add(item);
}
}
}
这个方法可以正常运行。但它会创建一个单独的List
并对其执行操作。是否有更好的方法,可以使用 .Net 内置的操作或在同一个List
上执行操作,而不需要创建这些临时List
等?
谢谢。
Select
。 - Vahid