C
C#3y ago
Iceman228

Remove list element

AddTabGroupChildren(Config.KpiSelection.TabHierarchy.TabBase);
private void AddTabGroupChildren(List<XmlTabBase> members)
{
members = members
.OrderBy(p => p.Order)
.ToList();

var children = members.OfType<XmlTabGroup>().ToLookup(group => group.GroupId);
foreach (var member in members.OfType<XmlTabGroup>().ToList())
{
member.TabBase.AddRange(new List<XmlTabGroup>(children[member.Order].ToList()));
member.TabBase = member.TabBase.OrderBy(p => p.Order).ToList();
if (member.GroupId != 0) members.RemoveAt(members.FindIndex(p => p.Order == member.Order));
}
}
AddTabGroupChildren(Config.KpiSelection.TabHierarchy.TabBase);
private void AddTabGroupChildren(List<XmlTabBase> members)
{
members = members
.OrderBy(p => p.Order)
.ToList();

var children = members.OfType<XmlTabGroup>().ToLookup(group => group.GroupId);
foreach (var member in members.OfType<XmlTabGroup>().ToList())
{
member.TabBase.AddRange(new List<XmlTabGroup>(children[member.Order].ToList()));
member.TabBase = member.TabBase.OrderBy(p => p.Order).ToList();
if (member.GroupId != 0) members.RemoveAt(members.FindIndex(p => p.Order == member.Order));
}
}
I have a method which takes a flat list and generates a tree from it. At the end I remove the elements from the list which have been added as a child. This is the part which isn't working anymore and I don't understand why. Meaning when I look at members inside the method, the list at the end is correct, but the actual property still has the deleted elements. The added children are correct though.
4 Replies
mikernet
mikernet3y ago
You're not removing from the list that is passed into the method You're removing from the new list you created inside the method
members = members
.OrderBy(p => p.Order)
.ToList();
members = members
.OrderBy(p => p.Order)
.ToList();
This creates a new list, so the list you passed into this method won't be affected.
Iceman228
Iceman228OP3y ago
Just figured that out as well. Thanks though.
mikernet
mikernet3y ago
Is there a reason you're doing members.RemoveAt(members.FindIndex(p => p.Order == member.Order)); instead of members.Remove(member)?
Iceman228
Iceman228OP3y ago
I am trying to think of one and don't find it. I will test it without.
Want results from more Discord servers?
Add your server