Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to remove items from a collection

Tags:

c#

collections

What is the best way to approach removing items from a collection in C#, once the item is known, but not it's index. This is one way to do it, but it seems inelegant at best.

//Remove the existing role assignment for the user. int cnt = 0; int assToDelete = 0; foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments) {     if (spAssignment.Member.Name == shortName)     {         assToDelete = cnt;     }     cnt++; } workspace.RoleAssignments.Remove(assToDelete); 

What I would really like to do is find the item to remove by property (in this case, name) without looping through the entire collection and using 2 additional variables.

like image 228
Dan Avatar asked Oct 16 '08 00:10

Dan


People also ask

How to Remove from collection c#?

RemoveAt(Int32) is used to remove the element at the specified index of the Collection<T>. Syntax: public void RemoveAt (int index); Here, index is the zero-based index of the element to remove.

What is a collection C#?

Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.


2 Answers

If RoleAssignments is a List<T> you can use the following code.

workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName); 
like image 173
JaredPar Avatar answered Oct 01 '22 00:10

JaredPar


If you want to access members of the collection by one of their properties, you might consider using a Dictionary<T> or KeyedCollection<T> instead. This way you don't have to search for the item you're looking for.

Otherwise, you could at least do this:

foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments) {     if (spAssignment.Member.Name == shortName)     {         workspace.RoleAssignments.Remove(spAssignment);         break;     } } 
like image 24
Jon B Avatar answered Sep 30 '22 22:09

Jon B