Reputation: 1220
If I try:
List<Student> students = new List<Student>();
List<Group> Groups = new List<Group>();
Groups = students.Remove(f => f.StudentID.Equals(studentID));
I get an error on this line: f => f.StudentID.Equals(studentID)
I am having difficulty from my previous posts here https://stackoverflow.com/questions/10116685/linq-deleted-users-still-associated-with-groups and here Delete method in WCF
So I thought maybe I could delete the students contained within groups but I get an error Cannot convert lambda expression to type Student because it is not a delegate type.
Just a quick up date as to what I am trying to do, lets say student A can belong to multiple Groups. Then if I delete that student the student should no longer list any groups. But it does. However if I search lets say Group Computing the student isnt there. Only seems to be when I take the student and search which groups he belongs to (even if he is deleted) it returns the group I originally added him to. THIS SHOULDNT HAPPEN ARGHH
Upvotes: 1
Views: 2127
Reputation: 31250
If you are trying to pass in the predicate, you have to use the RemoveAll method. Remove method takes in a single element
var numRemoved = students.RemoveAll(f => f.StudentID == studentID);
Also the RemoveAll method doesn't return the "updated" list, it updates the list. So students
would be updated list i.e. it would not have students with StudentID == studentID
.
If you want to preserve the students
as is, copy the elements to a new list
var newStudentList = new List<Student>(students);
and then filter that list
P.S. The common objects in both list are same i.e. if an object is updated in one list, it would get updated in the second list too. If a second copy is needed, deep cloning has to be implemented. This is just two lists from same pool of objects.
var numRemoved = newStudentList.RemoveAll(f => f.StudentID == studentID);
With your updates, it seems you are looking for
students.RemoveAll(s => s.StudentID == studentID);
Groups.ForEach(g => g.Groupsz.RemoveAll(gs => gs.StudentID == studentID));
Upvotes: 7
Reputation: 18142
List<T>.Remove()
has a return type of bool
. So you're not going to get a List<Group>
from List<Student>.Remove()
.
You can use var removed = students.RemoveAll(f => f.StudentID.Equals(studentID));
to get a list of which students were removed from list.
But you'll need to do a little more to get that list of students to be a List<Group>
. There is not enough information in your question to tell if a conversion possibility exists.
Upvotes: 2