简体   繁体   中英

Getting a list of parents from a List?

I'm writing a little C# program to scan a directory recursively and get the filesize of each file, a few other bits of information, and add it all to tables in a sqlite database. I've hit a bit of a snag, however - I want to get the directory data (Table structure below) and turn it into a List< Class > the Class being a class with the file data, directory data and a List of all of the directory's parents in order (Parent, grand parent, etc.).

Directory table:

id int
parentID int
directoryName string

How would I go about doing this? Getting a list of children is simple, but I'm finding that getting a list of parents is fairly difficult without repeatedly looping through the directory list.

I think that List<Class> is not the right class to use.

Depending on what you are going to do with your list, I would use a Dictionary<int, Class> if the order of your list is not important, otherwise SortedDictionary<int, Class> if you want it to be ordered by ID, or OrderedDictionary if you want to be able to specify a different way of sorting.

You can use DirectoryInfo.GetParent()

List<DirectoryInfo> parents = new List<DirectoryInfo>();
DirectoryInfo parent = di.Parent;
while(parent != null){
      parents.Add(parent);
      parent = di.Parent;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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