C#List<>按另一个List值排列

时间:2016-04-28 09:30:36

标签: c# list

我有一个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 };

如何获取新列表,以便我的结果像

List<string> Output = new List<string>(){ "B" ,"A" ,"C" ,"E" ,"D" ,"F" ,"G" }; 

P.S。我可以使用以下代码来获得结果。但我想学习另一种方法。

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

3 个答案:

答案 0 :(得分:5)

您可以使用LINQ根据索引进行排序:

var list = Source.Select((item, index) => new { Item = item, Index = Sequence[index] })
                 .OrderBy(s => s.Index)
                 .Select(s => s.Item);

首先,我使用Select获取Source中项目的索引,并在Sequence中找到相应的项目。然后我们对此进行排序并将原始项目恢复。

答案 1 :(得分:1)

或使用Zip:

var ordered = Source
    .Zip(Sequence, (source, seq) => new { Item = source, Index = seq })
    .OrderBy(s => s.Index)
    .Select(s => s.Item);

Zip在同一位置逐项配对两个枚举。 lambda表达式可以用来创建一些东西(在这种情况下是一个匿名方法),两个项目在同一个位置。

与其他解决方案相比,它不会调用

Sequence[index]

对于源中的每个项目。而是它将两个集合迭代在一起。这对于性能更好,并且允许在没有索引访问时执行相同操作(例如:使用两个IEnumerables)。

答案 2 :(得分:0)

这是一个LINQ版本:

var result =
    Source
    .Select((x,i) => new {Item = x, Index = i})
    .OrderBy(v => Sequence.IndexOf(v.Index + 1))
    .Select(v => v.Item)
    .ToList();
相关问题