按特定顺序排列的订购列表

2024-03-22

我有一个List我有新的顺序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 etc?

谢谢。


运行这样的排序时,您需要考虑性能。

如果您只期望少数元素,那么佩德罗的解决方案 https://stackoverflow.com/a/36276247/1110897 is OK.

如果您期望有很多元素(例如,100 个或 1000 个),那么搜索整个集合并不是一个好主意。tests对于中的每个元素newOrder。在这种情况下,使用Dictionary对于所有索引/排序顺序查找。尝试这样的事情:

List<Test> tests = new List<Test>() { 
    new Test(){ No = 101 },
    new Test(){ No = 201 },
    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 };

// Create a Dictionary/hashtable so we don't have to search in newOrder repeatedly
// It will look like this: { {201,0}, {401,1}, {300,2}, {101,3}, {601,4}, {500,5} }
Dictionary<int, int> newOrderIndexedMap = Enumerable.Range(0, newOrder.Length - 1).ToDictionary(r => newOrder[r], r => r);

// Order using 1 CPU
var orderedTests = tests.OrderBy(test => newOrderIndexedMap[test.No]);
// Order using multi-threading
var orderedInParallelTests = tests.AsParallel().OrderBy(test => newOrderIndexedMap[test.No]);

// Order using 1 CPU, when it's possible that a match will not be found in newOrder
var orderedTestsSafe = tests.OrderBy(test => 
    {
        int index;
        bool foundIndex = newOrderIndexedMap.TryGetValue(test.No, out index);
        return foundIndex ? index : Int32.MaxValue;
    });

请注意,这个答案和佩德罗的答案都假设newOrder包含中包含的所有值tests元素,反之亦然。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按特定顺序排列的订购列表 的相关文章

随机推荐