I'm using LINQ to build up a tree structure of objects from a collection of objects which were retrieved from a stored procedure call.
I want to know if
a) there is any way to remove elements from one collection to a new collection
b) if there is actually any point performance wise in doing this
my code looks something like this:
class MyEntity
{
int ID { get; set; }
int? ParentID { get; set; }
string Name { get; set; }
List<MyEntity> children = new List<MyEntity>();
List<MyEntity> Children { get { return children; } }
}
List<MyEntity> initialCollection = //get stuff from DB
List<MyEntity> rootElements = (from e in initialCollection
where e.ParentID == null
select e).ToList();
List<MyEntity> childElements = (from e in initialCollection
where e.ParentID != null
select e).ToList();
foreach(MyElement e in rootElements)
e.Children.AddRange((from c in childElements
where c.ParentID == e.ID
select c).ToList());
//do some more recursion
So basically; is there a way to do the select statement, where I actually remove the elements from initialCollection
as I select them. The idea being to reduce the number of elements to search through while recursively building up my tree. Would there actually be any benefit in doing this, or is the overhead of removing elements from one collection and adding to another too great?