sometimes, i just feel dumb…
i have a simple class:
public class myClass
{
public long Id { get; set; }
public long ParentChannelId { get; set; }
}
and i have a list that contains the class:
List<myClass> myItems = new List<myClass>
further down the code, i feed the list with classes.
now, i want to delete an item from the list.
but, since an item can have children and grandchilds etc…
i want to delete everything related..
was thinking of something like:
(pseudo code )
var List<myClass> itemsToDelete = myItems.Where(i => i.Ancestors.Contains(myItemId));
but i dont really have the brains atm to know how to write it exactly… :\
i do have the .Ancestors function…
just need help with the lambda linq
public List<Channel> Ancestors
{
get
{
List<MyCms.Content.Channels.Channel> result = new List<MyCms.Content.Channels.Channel>();
Channel channel = this;
while (channel != null)
{
result.Add(channel);
channel = myChannels.Where(c => c.ParentChannelId == this.Id).First();
}
result.Reverse();
return result;
}
}
EDIT: guess i did not explain myself as i should…
i have all the properties like ancestors, children parent etc…
i want to select all the classes that might contain the specific class…
I’ve re-read your question, especially the last part where you said you already have
.Ancestors, and now it makes more sense.Do this to get your list of items to delete:
Then you can
foreachthrough the result, and remove them from the original list.I’d suggest keeping these in a
Dictionary<int, MyClass>or aHashSet<MyClass>instead of a list, since removal will be way faster.For a
HashSet, you’ll have to implementEqualsandGetHashCode, or create anIEqualityComparer<MyClass>implementation to provide those methods.Before Edit:
I wouldn’t write my code this way. I’d simply create a
Dictionary<int, MyClass>instead of a list. It will do a lookup way faster than anything involving ancestors/tree traversal.But here is how to accomplish what you’re trying to accomplish:
If you’re using Linq to Objects (as opposed to Linq to SQL or Linq to Entities), make a property called
ParentonMyClass, of the correct type, instead of trying to link them byId.Then you can make an
Ancestorsproperty fairly easily:If you can’t edit the class, make an extension method called
GetAncestors.Then you can use something very similar to the code you wrote in your question:
Linq to Entities
If you are using Linq to Entities, create a navigation property of the type
MyClassto navigate to the parent, and do the same thing. Note that this might cause re-queries. Not sure the Linq can or would get translated into a hierarchical query.