简体   繁体   English

从C#中的最后一个对象开始循环

[英]looping starting from last object in c#

How can I loops the list of object strating from last position object in c#. 我如何循环从c#中最后一个位置对象开始的对象列表。 Here, I have asp.net mvc 3 application where I need to create the directory to upload the path according to the category available if directory is not available. 在这里,我有asp.net mvc 3应用程序,如果目录不可用,我需要在其中创建目录以根据可用的类别上载路径。 But list of category object are in opposite order where child category is at first position. 但是子类别位于第一位置的类别对象列表却是相反的顺序。 I want to create the folder of child category inside the parent category. 我想在父类别中创建子类别的文件夹。 so I want to start the loops in reverse order or is there any function to reverse the list of category object. 所以我想以相反的顺序启动循环,或者是否有任何功能可以反转类别对象的列表。 I have following foreach loops: 我有以下foreach循环:

    foreach (var item in parentcategory)
    {   
        categorypath += item.CategoryName + "/" ;
    }

any helps is greatly appreciated 任何帮助是极大的赞赏

Simpliest solution, but not most efficient is: 最简单但不是最有效的解决方案是:

parentcategory.Reverse();
foreach (var item in parentcategory)
{   
    categorypath += item.CategoryName + "/" ;
}

or: 要么:

for (int i=parentcategory.Count-1; i>=0; i--)
{   
    var item = parentcategory[i];
    categorypath += item.CategoryName + "/" ;
}

You actually don't have to loop in reverse. 实际上,您不必反向循环。

foreach (var item in parentcategory)
{   
    categorypath = item.CategoryName + "/" + categorypath;
}

Not terribly efficient but it works. 效率不高,但是可以。

You could also consider using System.IO.Path. 您也可以考虑使用System.IO.Path。

var categorypath = Path.Combine(categories.Reverse().ToArray());

Instead of appending to the string, you could also prepend: 除了附加到字符串之外,还可以添加前缀:

foreach (var item in parentcategory)
    {   
        categorypath = item.CategoryName + "/" + categorypath;
    }

Note that in all solutions presented so far, the resulting string has a trailing "/". 请注意,到目前为止,在所有提出的解决方案中,结果字符串都带有结尾的“ /”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM