This code:
_interestlist.ForEach(i => i.interests.RemoveAll(x => x.id == "1234"));
will delete all objects in the interests lists contained in any of your InterestList objects in _interestlist with id = "1234".
Question
I have a model class like this
public class InterestList
{
public string id { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Interest> interests { get; set; }
}
public class Interest
{
public string id { get; set; }
public int sortOrder { get; set; }
public string name { get; set; }
public string categoryName { get; set; }
public string categoryId { get; set; }
}
And an object private List<InterestList> _interestlist;
which holds my data.
as you can see _interestlist
contains a list
of Interest
named interests
now i want to remove a single entry of it. How can I achieve this with Linq?
I have tried like
_interestlist.RemoveAll(x => x.id == "1234");
but it removes interests
only not Interest
. Can any one point out the right way?
Solution 2
This code:
_interestlist.ForEach(i => i.interests.RemoveAll(x => x.id == "1234"));
will delete all objects in the interests lists contained in any of your InterestList objects in _interestlist with id = "1234".
OTHER TIPS
Technically you have a lists of lists, almost as if you had List<List<Interest>>
. To solve this problem you will need to foreach
over your collection and perform the Remove
operation on the inner list.
foreach(InterestList interestList in _interestlist)
{
interestList.interests.RemoveAll(x => x.id == "1234");
}
You also could use the ForEach
method built in to List<T>
_interestlist.Foreach(i => i.interests.RemoveAll(x => x.id == "1234"));