-2

Below is my code I'm working with in C#. I understand it's finding the mode for my set of data, but what I'm confused on is the GroupBy(value => value) and what exactly the => does because I can change value to anything and it still works. I would like to be able to use LINQ, I just need a deeper understanding as far as these parameters go.

static double Mode()
{
  double mode = valueArray.GroupBy(value => value)
        .OrderByDescending(value => value.Count())
        .First()
        .Key;
  return mode;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jon Butler
  • 41
  • 6
  • 1
    The => indicates a lambda. You should read the relevant documentation: https://msdn.microsoft.com/en-us/library/bb397687.aspx. – siride Sep 12 '16 at 03:19
  • oh awesome thank you – Jon Butler Sep 12 '16 at 03:22
  • Possible duplicate of [What does the '=>' syntax in C# mean?](http://stackoverflow.com/questions/290061/what-does-the-syntax-in-c-sharp-mean) – Mark Sep 12 '16 at 03:34

1 Answers1

0

Let's dissect different parts of your Linq Query. Here each call's result / output act as the Input for the next call to process the data

  1. valueArray.GroupBy(value => value)

GroupBy here has a same usage as in Sql, it leads to result in the format IEnumerable<IGrouping<Key,Value>>, lambda => is a glue, where it provides each an every element in the collection valueArray for processing. Only strange part is you take the whole object as a Key, so the Result will be same object as key and value in this case. In case, if it's a custom class / reference type and not primitive type, then override Equals and GetHashcode methods for the correct operation, else it will do reference comparison of the objects. Your case key seems to be double - primitive type, which is fine

  1. OrderByDescending(value => value.Count())

This shall be simple, take the Count of the IGrouping elements, for each Grouping and arrange in the descending order. Result is IOrderedEnumerable<IGrouping<Key,Value>>, which are arranged by the grouped elements Count

  1. First()

Take First element with maximum count value i.e Only one IGrouping<Key,Value> is selected

  1. Key

Take the Key of the First element, and return as a result

Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74