0

Maybe I'm doing this incorrectly, but I'm trying to shuffle a List by casting it into a HashSet,

List<Article> art = new List<Article>(rootobject.articles);
HashSet<Article> setart = new HashSet<Article>(art);

When I iterate through both the List,

foreach (Article a in art)
{
    Console.WriteLine(a.title)
}

and the Hashset,

foreach (Article a in setart)
{
    Console.WriteLine(a.title)
}

I get exactly the same output in exactly the same order. I was thinking that use the cast operation should randomize the List by default but that appears to not be the case.

Where am I going wrong?

insomniac
  • 192
  • 1
  • 3
  • 16
  • 1
    Why do yo think that putting data into a hashset will shuffle it? – Sean Apr 07 '20 at 07:44
  • 1
    How `Article` is implemented? Does it have `GetHashCode` and `Equals` method overriden? Please, also refer to remarks section of [hashset](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=netframework-4.8#remarks) – Pavel Anikhouski Apr 07 '20 at 07:44
  • If you want to shuffle a list, you can swap the first element with a random one, the second element with a random one, ..., the n-th element with a random one. – SomeBody Apr 07 '20 at 07:45
  • 4
    `HashSet` does *not guarantee* insertion order; the order can depend on .Net version, items itself etc. nor `HashSet` *shuffle* the items. Items just *can* (not *must*) be in arbitrary order – Dmitry Bychenko Apr 07 '20 at 07:48
  • See the duplicates for an answer to your question, and a better way to sort the list in random order. – mjwills Apr 07 '20 at 08:33
  • Pavel - no methods have been overridden, but I will just shuffle the list in situ. Thanks. – insomniac Apr 07 '20 at 08:37

1 Answers1

-1
public HashSet(IEnumerable<T> collection);

calls this constructor:

public HashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer);

and if the collection is not already a HashSet there is a foreach which copies the items within the collection in an order depending on the GetHashCode()-Function from the underlying object.

That way it is possible that your HashSet has not the exact order from your List. But as you see in your example, it is possible that the order is still the same.

This is a reference to the HashSet.cs code.

https://github.com/microsoft/referencesource/blob/master/System.Core/System/Collections/Generic/HashSet.cs

Edited my answer, thanks to the replies.

Foxenstein
  • 84
  • 5