2016-01-23 41 views
2

我有我创建的自定义列表,其中包含完整的文件夹路径和相应的版本号。我将这两个值都存储在一个列表中。我想让他们获得存储在列表中的最高X版本及其相应的文件夹路径。我一直在努力,但现在需要帮助。到目前为止,我已经得到了代码如下:订购和从自定义列表中获取数据 - C#

这是我的列表类:

class versionFolder 
{ 
    public int version { get; set; } 
    public string folderDIR { get; set; } 

    public versionFolder(int version, string folderDIR) 
    { 
     this.version = version; 
     this.folderDIR = folderDIR; 
    } 

} 

这里是我创建列表和添加项目到它的代码。在底部,我想打印列表中的内容(版本和文件夹路径),然后在底部,我想获得由深度变量设置的最高X版本。

public highestVersion(string dsPath, int depth) 
    { 
     int num = depth; 
     List<versionFolder> allVersions = new List<versionFolder>(); //list to hold all version numbers and full path 

     string folder = dsPath; 
     string[] versionDIRS = Directory.GetDirectories(folder); 

     foreach (string folderr in versionDIRS) 
     { 
      string[] fullpath = folderr.Split('\\'); 

      string folderName = fullpath[fullpath.Length - 1]; //returns VXX-XXXXXXXX (version folder name) 
      string vString = "6"; //sets a version number, this is actually data extrapolated from the folder path 
      allVersions.Add(new versionFolder(Convert.ToInt32(vString), fullpath.ToString())); 
     } 



     foreach (var version in allVersions) 
     { 
      Console.WriteLine("Amount is {0}", version.version); 
      Console.WriteLine("Amount is {0}", folderDIR.folderDIR); 
     } 
     var testtt = allVersions.OrderByDescending(n => n.version).Take(Convert.ToInt32(num)); 
     Console.Write("Test:" + testtt); 
    } 

输出对于版本号很好,但我无法获得folderDIR。 为获得最高的X值输出返回此:

Test:System.Linq.Enumerable+<TakeIterator>d__3a`1[Importer.versionFolder] 

任何帮助将非常感激。

编辑:我想这可能是值得一提的是,我在使用.NET 3.5

+0

at:allVersions.Add(new versionFolder(Convert.ToInt32(vString),fullpath.ToString()));您正在将完整路径字符串数组转换为字符串。但实际版本文件夹的文件夹字符串不是字符串数组格式 – SarveshwarPM

回答

2

Take()方法的返回值类型是IEnumerable,如果你想获得的返回类型List<T>,只需拨打ToList()方法。如果您只想获得foldDir字段,则请拨打Select方法。

public IList<string> HighestVersion(int topCount) 
    { 
     List<VersionFolder> vfList = new List<VersionFolder> 
     { 
      new VersionFolder(1, "A"), 
      new VersionFolder(4, "B"), 
      new VersionFolder(3, "C") 
     }; 

     vfList = vfList.OrderBy(v => v.Version).Take(topCount).ToList(); 

     foreach (VersionFolder versionFolder in vfList) 
     { 
      Console.WriteLine(versionFolder.FolderDir); 
     } 

     //return folderDir only 
     return vfList.Select(v=>v.FolderDir).ToList(); 
    } 
+0

非常感谢。它的工作原理是它获得最高的X值,但输出是: System.String [] System.String [] System.String []。 我猜这是因为versionFolder.FolderDIR是一个数组?对不起,我对此有点新鲜。谢谢你的帮助。 – SteveMaybes

+0

@SteveMaybes对不起,我想你有另外一个问题,这是由这一行'allVersions.Add(new versionFolder(Convert.ToInt32(vString),fullpath.ToString()));','fullpath'是一个数组,如果你想将它转换为字符串,可以使用'string.Join(“,”,fullpath)'而不是'fullpath.ToString()'。 – Zen