有没有办法用一行代码添加到列表中的两个变量?

时间:2014-08-14 22:36:35

标签: c# .net

int[,] map = new int[,]
{
 {1,1,1,0,0,0,0,0,},
 {0,0,1,0,0,0,0,0,},
 {0,0,1,1,0,0,1,1,},
 {0,0,0,1,0,0,1,0,},
 {0,0,1,1,0,0,1,0,},
 {0,0,1,0,0,0,1,0,},
 {0,0,1,1,1,0,1,0,},
 {0,0,0,0,1,1,1,0,},
};

int[,] map1 = new int[,]
{
 {0,0,0,1,1,1,1,0,},
 {0,0,0,1,0,0,1,0,},
 {0,0,0,1,1,0,1,0,},
 {1,1,0,0,1,0,1,0,},
 {0,1,0,0,1,0,1,0,},
 {0,1,1,1,1,0,1,0,},
 {0,0,0,1,1,0,1,1,},
 {0,0,0,0,0,0,0,0,},
};

        private List<Texture2D> tileTextures = new List<Texture2D>();
        private List<int[,]> MapsArrays = new List<int[,]>();

        public void AddMaps()
        {
            MapsArrays.Add(map);
            MapsArrays.Add(map1);
        }

现在我正在添加(地图)然后添加(map1)...但是如果我有时会有30个地图变量。 我怎样才能将它们全部自动添加到循环中以使所有变量以map开始并添加它们?

3 个答案:

答案 0 :(得分:0)

听起来你正在寻找AddRange扩展方法:

MapsArrays.AddRange(new [] { map, map1 });

请注意,您可能需要将MapsArrays转换为List<Map>才能使其发挥作用。

(不要害怕尝试西蒙的解决方案,它一点也不差)

答案 1 :(得分:0)

还有另一种方式我会投入其中。

如果不知道您的确切结构,我只会说“将它们添加到内联”。也就是说,不要单独声明它们,只需将它们直接添加到列表中即可。另一个选项是查找词典:

private IDictionary<string, int[,]> maps = new Dictionary<string, int[,]>();

public void Init() {
    maps.Add("map", new int[,]
        {
         {1,1,1,0,0,0,0,0,},
         {0,0,1,0,0,0,0,0,},
         {0,0,1,1,0,0,1,1,},
         {0,0,0,1,0,0,1,0,},
         {0,0,1,1,0,0,1,0,},
         {0,0,1,0,0,0,1,0,},
         {0,0,1,1,1,0,1,0,},
         {0,0,0,0,1,1,1,0,},
        });

    maps.Add("map1", new int[,] ... // second one here
}

如果您需要引用它们,这具有快速查找的好处..但也允许您只声明一次映射(它们被添加到字典中)。然后你可以通过他们的密钥来引用它们:

var map1 = maps["map1"];

答案 2 :(得分:0)

要在一行中执行此操作,您可以创建自己的扩展方法:

public static class Extensions
{
    public static void AddMany<T>(this List<T> list, params T[] input)
    {
        list.AddRange(input);
    }
}

你可以这样使用:

public void AddMaps()
{
    MapsArrays.AddMany(map, map1, map2);
}