Best way to remove items from a collection

前端 未结 15 2022
天命终不由人
天命终不由人 2020-12-08 05:47

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 be

相关标签:
15条回答
  • 2020-12-08 06:49

    Here is a pretty good way to do it

    http://support.microsoft.com/kb/555972

            System.Collections.ArrayList arr = new System.Collections.ArrayList();
            arr.Add("1");
            arr.Add("2");
            arr.Add("3");
    
            /*This throws an exception
            foreach (string s in arr)
            {
                arr.Remove(s);
            }
            */
    
            //where as this works correctly
            Console.WriteLine(arr.Count);
            foreach (string s in new System.Collections.ArrayList(arr)) 
            {
                arr.Remove(s);
            }
            Console.WriteLine(arr.Count);
            Console.ReadKey();
    
    0 讨论(0)
  • 2020-12-08 06:51

    There is another approach you can take depending on how you're using your collection. If you're downloading the assignments one time (e.g., when the app runs), you could translate the collection on the fly into a hashtable where:

    shortname => SPRoleAssignment

    If you do this, then when you want to remove an item by short name, all you need to do is remove the item from the hashtable by key.

    Unfortunately, if you're loading these SPRoleAssignments a lot, that obviously isn't going to be any more cost efficient in terms of time. The suggestions other people made about using Linq would be good if you're using a new version of the .NET Framework, but otherwise, you'll have to stick to the method you're using.

    0 讨论(0)
  • 2020-12-08 06:52

    A lot of good responses here; I especially like the lambda expressions...very clean. I was remiss, however, in not specifying the type of Collection. This is a SPRoleAssignmentCollection (from MOSS) that only has Remove(int) and Remove(SPPrincipal), not the handy RemoveAll(). So, I have settled on this, unless there is a better suggestion.

    foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
    {
        if (spAssignment.Member.Name != shortName) continue;
        workspace.RoleAssignments.Remove((SPPrincipal)spAssignment.Member);
        break;
    }
    
    0 讨论(0)
提交回复
热议问题