从字典中获取值列表

时间:2015-03-04 12:54:27

标签: c# dictionary

我是c#的初学者,我正在尝试获取值列表,但我得到一个空对象引用。

我有一本字典

var stripes = new Dictionary<int, List<Transform>>();

我正在尝试获取转换列表

       foreach (var stripe in stripes)
            {
                List<Transform> transforms = stripe.Value;
                foreach (var treeTransform in transforms)
                {
                    float distance = DistanceToCameraPlane(treeTransform.position);
                    TreeObject treeObject = new TreeObject();
                    treeObject.distance = distance;
                    treeObject.tree = treeTransform;
                    sortedTrees.Add(treeObject);
                }
            }

但是我在treeTransform.position

中得到了一个空对象引用

2 个答案:

答案 0 :(得分:1)

尝试更改此行:

foreach (var stripe in stripes)

改为:

foreach (List<Transform> transforms in stripes.Values)

并删除此内容:

List<Transform> transforms = stripe.Value;

答案 1 :(得分:0)

foreach (var stripe in stripes)
            {
                List<Transform> transforms = stripe.Value;
                if (transforms != null && transforms.Count > 0)
                {
                    foreach (var treeTransform in transforms)
                    {
                        if (treeTransform != null)
                        {
                            float distance = DistanceToCameraPlane(treeTransform.position);
                            TreeObject treeObject = new TreeObject();
                            treeObject.distance = distance;
                            treeObject.tree = treeTransform;
                            sortedTrees.Add(treeObject);
                        }
                    }
                }
            }