从集合中删除项目的最佳方法

编程入门 行业动态 更新时间:2024-10-24 06:26:49
本文介绍了从集合中删除项目的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

什么是接近从集合在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; } }

更多推荐

从集合中删除项目的最佳方法

本文发布于:2023-11-01 18:30:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   项目

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!