Jon
Jon

Reputation: 385

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.

Upvotes: 0

Views: 114

Answers (2)

Francesco Baruchelli
Francesco Baruchelli

Reputation: 7468

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.

Upvotes: 1

user1519979
user1519979

Reputation: 1874

You can use DirectoryInfo.GetParent()

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

Upvotes: 0

Related Questions