元素字段列表

时间:2018-11-23 15:37:29

标签: c# performance linq element

我可以使用Dictionary<long,MyObj>将字典.Values转到一个列表,其中MyObj的{​​{1}}字段名为Vector3

我想要一个位置列表(值类型):position,像这样:MyObj.position

性能至关重要。

是否可以用LINQ或其他方式在C#中实现此目标?

List<Vector3> positions

1 个答案:

答案 0 :(得分:1)

因此,使用以下代码:

    public static void Main(string[] args)
    {
        var stopwatch1 = new Stopwatch();
        var dictionaryTest = GetDictionary(1000);

        stopwatch1.Start();

        var results = dictionaryTest.Values.Select(x => x.Position).ToList();

        stopwatch1.Stop();

        var stopwatch2 = new Stopwatch();
        stopwatch2.Start();

        var results2 = dictionaryTest.Select(obj => obj.Value.Position).ToList();

        stopwatch2.Stop();

        var stopwatch3 = new Stopwatch();
        stopwatch3.Start();

        var myList = new List<double>();

        foreach (var pair in dictionaryTest)
        {
            myList.Add(pair.Value.Position);
        }

        stopwatch3.Stop();

        Console.WriteLine("results1: " + stopwatch1.Elapsed);
        Console.WriteLine("results2: " + stopwatch2.Elapsed);
        Console.WriteLine("results3: " + stopwatch3.Elapsed);
        Console.Read();
    }

    public static Dictionary<long, MyUser> GetDictionary(int numberOfRows)
    {
        var d = new Dictionary<long, MyUser>();

        for (int i = 0; i < numberOfRows; i++)
        {
            d.Add(1000 + i, new MyUser { Age = 10 + i, Position = 100.01 + i });
        }

        return d;
    }

这带回来了:

enter image description here

所以foreach看起来是我的机器上提出的3个中最快的。不过值得测试一下自己。

选择“优化代码”:

enter image description here