我有一个List,我想按另一个序列列表排序.
List<string> Source = new List<string>() { "A" ,"B" ,"C" ,"D" ,"E" ,"F" ,"G" };
List<int> Sequence = new List<int>(){ 2, 1, 3, 5, 4, 6, 7 };
Run Code Online (Sandbox Code Playgroud)
如何获取新列表以便我的结果如此
List<string> Output = new List<string>(){ "B" ,"A" ,"C" ,"E" ,"D" ,"F" ,"G" };
Run Code Online (Sandbox Code Playgroud)
PS我可以使用以下代码来获得结果.但我想学习另一种方法.
private List<string> ArrangeList(List<string> i_lsData, List<int> i_nSequence)
{
List<string> lv_lsTempList = new List<string>();
foreach(int Temp in i_nSequence)
{
lv_lsTempList.Add(i_lsData[Temp]);
}
return lv_lsTempList;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用LINQ根据索引进行排序:
var list = Source.Select((item, index) => new { Item = item, Index = Sequence[index] })
.OrderBy(s => s.Index)
.Select(s => s.Item);
Run Code Online (Sandbox Code Playgroud)
首先,我使用Select获取项目的索引Source并找到相应的项目Sequence.然后我们对此进行排序并返回原始项目.
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |