简体   繁体   中英

HashSet c# element in HashSet modify

how is it possible to modify a element in HashSet?

my HashSet looks like:

HashSet<int> mynumbers = new HashSet<int>();
mynumbers.Add(rnd.Next(1, 11));
mynumbers.Add(rnd.Next(1, 11));

the output can be done with:

Console.WriteLine( mynumbers.ElementAt(0) + "and" + mynumbers.ElementAt(1));

looks like for example:

2 and 10

but how can i now modify the first value in the HashSet.

this is not possible:

mynumbers.ElementAt(0) = 1; 

Since the items in that particular hash set are immutable you can't mutate the item. You would need to be adding items of a mutable type in order to mutate them (and even then, you'd be causing major problems for yourself if you mutated it in such a way that changed the equality or hash code of that object).

You can remove that item from the set and add a new one (using the methods of the corresponding names for those actions), but that's in no way changing the item that you added.

And of course a HashSet is an unordered collection, there is no "first" item in the collection, a given object simply is or isn't in the collection, it's not in the collection at a given position. If you need the items in your collection to have a position, then you'll need to use a different type of collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM