按特定订单排序列表

Tim*_*rty 5 .net c#

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


        }

    }
Run Code Online (Sandbox Code Playgroud)

这很好用.但它会在其上创建一个单独的List并执行操作.有没有更好的方法我可以使用内置的.Net操作或者可以在List不创建这些Temp List等的情况下执行相同的操作?

谢谢.

Ser*_*rge 7

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

如果您只想要少量元素,那么Pedro的解决方案就可以了.

如果你希望有很多元素(比如100或1000),那么搜索tests每个元素的整个集合并不是一个好主意newOrder.在这种情况下,使用a 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;
    });
Run Code Online (Sandbox Code Playgroud)

请注意,这个答案和Pedro都认为newOrder包含tests元素中包含的所有值,反之亦然.