Vishal
Vishal

Reputation: 6378

Remove items from a collection in entity framework

I have a function as below :

IEnumerable<Group> GetAllChildren(int parentID)
{
    using (Entities db = new Entities())
    {
        var result = (from x in db.Groups
                      where x.ParentID == parentID
                      select x).ToList();
        foreach (Group child in result.ToList())
        {
            result.AddRange(GetAllChildren(child.GroupID));
        }
        return result;
    }
}

In the above function if I pass a group name I get all the children at all levels. It works as expected.

Now my query looks like something like :

GroupNamesWithCorrespondingEffects 
    = new ObservableCollection<GroupNameWithCorrespondingEffect>
                (from g in db.Groups
                 select new GroupNameWithCorrespondingEffect
                            {
                                GroupID = g.GroupID,
                                GroupName = g.GroupName,
                                CorrespondingEffect = g.Master_Effects.Effect
                            }
                );

The above query will give me all the groups.

Now I want to remove all the groups from GroupNamesWithCorrespondingEffects that are children of a group with id == 25.

I have tried .Remove(GetAllChildren(25)) in 2nd query. but I get following error.

Collection.Remove(GroupNameWithCorrespondingEffect) has some invalid arguments.

Upvotes: 0

Views: 72

Answers (1)

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

hope this help you:

var childs = GetAllChildren(25).ToList();
var childIDList = childs.select(u => u.GroupID).ToList();

GroupNamesWithCorrespondingEffects = GroupNamesWithCorrespondingEffects
    .Where(u => !childIDList.Contains(u.GroupID)).ToList();

Upvotes: 1

Related Questions