简体   繁体   中英

How to find (and remove) a nested object from a List

hope someone can help. I have an object:

public class folder
{
    public string folderName { get; set; }
    public string folderPath { get; set; }
    public List<folder> subFolders { get; set; }
}

as you can see the object contains an object referencing itself allowing me to build up a list of folders and sub folders, I then have a

List<folder> mycustomlist ect..

to store this in. This list can be extremely deep and works fine when binding to a treeview or custom listview.

My problem is trying to remove a nested folder from the List, I can get the object but when using

mycustomlist.Remove(thefolder) 

it cant seem to locate the nested object to remove it.

I've tried several ways using Linq but with no joy, maybe their is a better way of doing this?

Hope someone can help,

Thanks

Nath

it cant seem to locate the nested object to remove it.

Remove is not recursive. It only removes an item directly in the list.

If thefolder is in a sublist then you'll need to recursively search for that and then remove it from the list it's actually in.

private bool RecursiveRemove(folder thisList, folder thefolder)
{
    if (thisList.Contains(theFolder))
    {
        thisList.Remove(theFolder);
        return true;
    }
    else
    {
        foreach (var folder in thisList.subFolders)
        {
            if (RecursiveRemove(folder, theFolder))
            {
                return true;
            }
        }
    }

    return false;  // not found
}

The List doesn't know it's recursive. It does not, and cannot, know what properties its items have, or what they mean. Is theFolder in mycustomlist , or in a list belonging to an item in mycustomlist (or a child of a child, etc.)?

If you want one function to remove a given item from anywhere in this tree structure you've created, regardless of which particular root or child list it lives in, you'll have to write your own recursive method to do that.

This is what I have got for this

    public void RemoveFolder(Folder folder, List<Folder> folderList)
    {
        if (folderList != null)
        {
            if (folderList.Contains(folder))
            {
                folderList.Remove(folder);
            }
            else
            {
                foreach (var subFolder in folderList.Select(x => x.subFolders))
                {
                    RemoveFolder(folder, subFolder);
                }

            }
        }
    }

But I think you will need to write your own equity comparer

See here List.Contains is not working as hoped

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