Reputation: 309
How to remove items in Entity Collection?
ex:
I have two entities that is related to each other
Employee and Reference
**Table: Employee**
EmployeeId(PK)
**Table: Reference**
ReferenceId(PK)
EmployeeId(FK)
Name
first I Initialize this:
Employee empCol = new Employee();
Reference refs = new Reference();
and then I save some data in the Entity Collection
refs.Name = "Sample";
empCol.References.Add(refs);
refs.Name = "Sample2";
empCol.References.Add(refs);
I want to remove the second element in the collection, how can I do that?
[0]= {Name = "Sample"}
[1]= {Name = "Sample2"}
I try this kind of code but it is not working, this code does not removing the second element in my Entity Collection, but it is not producing errors:
empCol.References.ToList().RemoveAt(1);
Upvotes: 1
Views: 3762
Reputation: 139
You can use all the List methods to remove items if you convert your EntityCollection into a List using toList(), for example
List<RotateArticle> articles = RotateArticle.GetDataByCategoryId(sm,currentArticle.MainCategory.Key).ToList();
and then
articles.Remove(articles[i]);
or
articles.RemoveRange(2, articles.Count - 1);
Upvotes: 0
Reputation: 309
I try to remove the object in the collection according to it's index
in the collection and it work
var refs = empCols.References.ElementAt(1);
empCols.References.Remove(refs);
Upvotes: 1
Reputation: 30728
Dont assume how index
is maintained inside by collection
. Find the object first
, and then remove
it from collection
var ref = empCol.References.FirstOrDefault( r=> r.Name == "Sample");
if (ref != null)
empCol.References.Remove(ref);
If you want to remove by index
, Find that index first.
Upvotes: 5