在数组中执行foreach

时间:2015-02-14 18:23:32

标签: c# arrays foreach

我正在尝试做一个foreach循环,它会选择我的数组中的每个字符串并将其添加到路径中,这是一个字符串并存储图像的路径,这是我到目前为止所做的:

string[] Images = new string[] { "Star_00001.png", "Star_00002.png", "Star_00003.png" };
string Path = "Assets/Images/";

        if (LevelUp)
        {
            foreach()
            {

            }
        }

正如你所看到的,我希望foreach循环遍历Images数组中的每个字符串,对于Images数组中的每个字符串,我希望将它添加到路径字符串中,所以最终结果例如是“Assets /”图像/ Star_00001.png“

有谁知道我应该怎么做?

3 个答案:

答案 0 :(得分:1)

foreach循环的语法为:

foreach(T ident in collection) {

T元素类型,ident变量名称和collection支持IEnumerable接口的对象。

所以你可以实现:

string[] images = new string[] { "Star_00001.png", "Star_00002.png", "Star_00003.png" };
string path = "Assets/Images/";
if (LevelUp) {
    foreach(string file in images) {
        string thepath = Path.Combine(path,file);
        //do something with file or thepath, like
        Console.WriteLine(thepath);
    }
}

最后需要注意的是,C#的共识是变量以小写开头,并且类型名称以大写开头。

答案 1 :(得分:1)

string[] Images = new string[] { "Star_00001.png", "Star_00002.png", "Star_00003.png" };
string path = "Assets/Images/";

if (LevelUp) 
    Images = Images.Select(image => Path.Combine(path, image)).ToArray();

答案 2 :(得分:1)

建议不要使用字符串连接生成文件路径。建议的方法是使用System.IO中提供的Path.Combine。请考虑以下示例:

        string[] Images = new string[] { "Star_00001.png", "Star_00002.png", "Star_00003.png" };
        string path = "Assets/Images/";

        if (LevelUp)
        {
            foreach (string s in Images)
            {
                // You can store result in an array or sth depending on what you
                // are trying to achieve
                string result = Path.Combine(path, s);
            }
        }
相关问题