设置集合保留插入顺序
我需要一个行为类似于 Set 并保留元素插入顺序的集合。
有没有或者我必须自己实现?
最好的实施是什么?
I need a collection that behaves as Set and preserves order of element insertion.
Is there one or I'll have to implement it myself?
What would the best implementation be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它在 .NET 中不存在,但您可以使用
List
和Distinct
LINQ 扩展方法来模拟它,这应该保留底层List 的顺序
。It doesn't exist in .NET, but you can emulate it using a
List
and theDistinct
LINQ extension method, which should preserve the order of the underlyingList
.OrderedDictionary
做你想做的事?尽管它不是通用的(意味着它返回的所有内容都必须进行强制转换或拆箱)并且是一个字典(不是集合),但它会按照您想要的方式运行。您可以轻松地使用一些任意值(例如
null
或true
)作为值,并让键成为集合的成员。这是一个可能的实现:
Will an
OrderedDictionary
do what you want?Although it is not generic (meaning everything it returns has to be cast or unboxed) and is a dictionary (not a set), it will behave the way you want. You could easily just use some arbitrary value like
null
ortrue
as values and let the keys be the members of your set.Here's a possible implementation:
创建一个很容易:
警告:通过
.Add(T)
插入重复项将导致ArgumentException
,这与其他情况不同,一个HashSet
在这种情况下只会返回false
。It is easy to create one:
Caveat: Inserting duplicate items via
.Add(T)
will result inArgumentException
s, which differs from, say, aHashSet<T>
which will just returnfalse
in that case.List inCountryList = new ArrayList();
。
。
。
设置 CountrySet = new LinkedHashSet( inCountryList );
LinkedHashSet 不允许重复,且不能保持插入顺序。
List inCountryList = new ArrayList();
.
.
.
Set countrySet = new LinkedHashSet( inCountryList );
LinkedHashSet doesn't allow duplication, nad maintain insertion order.
我意识到这是一篇旧帖子,但我最近需要类似的东西,并且认为如果有人想要一个维护添加顺序项目的通用序列(以及允许您在任何给定项目之前和之后插入),那么此实现可能会有所帮助)。我确信有人有更有效的方法来完成这项工作,但这确实有效。
I realize this is an old post, but I had a need for something similar recently, and thought this implementation might help if someone wants a generic sequence that maintains the order items are added (as well as lets you insert before and after any given item). I'm sure someone has more efficient ways to get this done, but this does the trick.