从集合中删除项目的最佳方法 [英] Best way to remove items from a collection

查看:120
本文介绍了从集合中删除项目的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是接近从集合在C#中删除的项目,一旦该项目被称为最好的办法,但不是指数。这是做这件事,但它充其量看起来不太优雅。

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);



我真的很想做的是找到该项目按属性删除(在这种情况下,名称)无需通过整个集合循环,并使用2个额外的变量。

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.

推荐答案

如果你想通过一个访问集合的成员它们的属性,你可以考虑使用词典< T> KeyedCollection< T> 来代替。这样你就不必寻找你要找的项目

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;
    }
}

这篇关于从集合中删除项目的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆