Using HashSet.orderBy() function

c# hashset vs list
difference between hashset and list in c#
c# sorted hashset
hashset contains c#
c# hashset get first element

Trying to sort:

HashSet<int> objHash = new HashSet<int>();
objHash.Add(14);
objHash.Add(12);
objHash.Add(11);
objHash.Add(13);

HashSet contians method OrderBy() with definition:

IOrderEnumerable<int> IEnumerable<int>.OrderBy<int,TKey>(Func<int,TKey>keySelector)

Trying to understand description:

IOrderEnumerable<int>- function OrderBy() returns

IEnumerable<int> - extension method defined in IEnumerable<int>. Can I somehow see body of this method?

.OrderBy<int,TKey>(Func<int,TKey>keySelector) - keySelector is function delegate with parameter of type int that returns TKey

Please, correct where my description interpretation is wrong.

How to use this function to order items in objHash according custom defined rules?

You are reading the quick info on the function correctly. To sort by your custom logic, you need to define what will be the return type as Tkey and pass the function that matches the delegate. The order by will then sort based on the returned value.

public static void Main()
{
    var h = new HashSet<int> () {1, 2, 3, 4, 5};

    var d = h.OrderBy<int, int>(x => MyFunc(x));

    foreach(var a in d)
        Console.WriteLine(a); //will order based on the returned value of MyFunc(x). in descending order.
        // output will be 5 4 3 2 1 instead of 1 2 3 4 5.
}

public static int MyFunc(int x) 
{
    return x * -1;
}

And of course, if your Tkey is an object, you should want to implement IComparable to tell how to sort that object.

HashSet.OrderBy C# (CSharp) Code Examples, How to sort HashSet in Java. Given a HashSet in Java, the task is to sort this HashSet. Adding elements into HashSet using add(). set.add( "geeks" );. set.​add(  C# (CSharp) HashSet.OrderByDescending - 17 examples found. These are the top rated real world C# (CSharp) examples of HashSet.OrderByDescending extracted from open source projects. You can rate examples to help us improve the quality of examples.

The OrderBy() method accepts the elements of your collection of objects (in your case, it is an int collection) and it should return a key for each specific object in the collection. Those returned keys are what will be used to sort the collection. Notice that these returned keys should be comparable between each other, so that the sorting can be performed.

Let's say you want to sort your numbers, while separating even numbers from odd numbers. A naive way of doing this would be making OrderBy() return string-typed keys, while placing a "0" character prefix on even numbers and a "1" character prefix on odd numbers, like that:

Number   Returned key
14       "014"
12       "012"
11       "111"
13       "113"

Then you can do it like:

var ordered = objHash.OrderBy(n => $"{n % 2}{n}");
foreach (var x in ordered)
    Console.WriteLine($"   {x}");

This would output numbers in the following order: 12, 14, 11, 13 (first the ordered even numbers, followed by the ordered odd numbers). Notice how the returned string keys were used for comparison/sorting of the set of numbers.

Of course the lexicographical ordering here only works fine because numbers have the same length... But again: this is just a naive example of how to use the OrderBy() method.

How to sort HashSet in Java, Sorting ArrayList using sort() method of List in Java 8 · ArrayList · HashSet · Java · List interface · Set interface · sorting · string  Sorts the elements of a sequence in ascending order by using a specified comparer. OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) Sorts the elements of a sequence in ascending order according to a key.

keySelector is function delegate with parameter of type int that returns TKey

Yes this is correct.

How to use this function to order items in objHash according custom defined rules?

Firstly, note that OrderBy is an extension method on IEnumerable and not a contained method of HashSet.

if you want to order the elements via the OrderBy extension method then you'd pass x => x as the keySelector function:

var orderedEnumerable = objHash.OrderBy(x => x); // or any other logic as long as the function takes an int and returns TKey

Note that this doesn't modify the source and it wouldn't make sense to sort a HashSet anyway as by definition it does not care about order.

As explicitly stated in the documentation:

The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

it then goes on to say:

A HashSet<T> collection is not sorted and cannot contain duplicate elements. If order or element duplication is more important than performance for your application, consider using the List<T> class together with the Sort method.

Emphasis mine.

if you want to maintain a sorted set then consider using SortedSet as it's documented as:

Represents a collection of objects that is maintained in sorted order.

HashSet<T> Class, I like. sort() method you can sort ArrayList in ascending and descending order in Java. used to sort the elements of List. java. sort() How to sort HashSet using TreeSet. A Comparator is a comparison function, which provide an ordering for​  The HashSet<T> collection type was first introduced in C# v3 and with .NET 3.5. This article will explore features of Hashset and also compare its performance with List.

SortedSet<T> Class, After that we have converted our HashSet to ArrayList and sorted it using Collections.sort() method. You can see elements in sorted order in our second print  HashSet in Java The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time.

How to Sort HashSet in Java - 2 ways, sort() in order to sort the list in decreasing order. In the below example we have used the following statement for sorting in reverse order. Collections.sort(arraylist​,  The HashSet<T> class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<TKey,TValue> or Hashtable collections. In simple terms, the HashSet<T> class can be thought of as a Dictionary<TKey,TValue> collection without values.

Sort arraylist in java without collections, sort() method where you can pass List as an argument. Convert HashSet to TreeSet by using constructor of the TreeSet class. Since TreeSet is a  While dealing with HashSet we may come across a situation where we need to sort it explicitly. we need to write a logic to sort them when required. In this article we are going to see an example where we are sorting a HashSet using two different methods. /* Program to Sort a HashSet using two different * methods.

Comments
  • Note that you cannot order the elements within the HashSet itself. OrderBy returns an IEnumerable that lets you iterate over the elements of the hashset in an ordered manner. The hashset itself remains "unordered", so to speak. If you want to have the HashSet itself ordered, use a SortedSet instead of a HashSet...
  • HashSet does not contain the method OrderBy - OrderBy is an extension method (as seen in the description) on IEnumerable<> that returns a new IOrderedEnumerable<>.
  • How I can find OrderBy method body?
  • I think it would be good to specify that OrderBy is an extension method on IEnumerable and not a contained method of HashSet. Also note there is nothing about an extension method that says it can't modify its first argument, nor does it need to return a new object.
  • @NetMage Right. edited to remove ambiguity. thanks again.