How to Use LINQ to Find the Max in a List

How to Use LINQ to Find the Max in a List thumbnail
LINQ can be extended to process other data sources.

Language Integrated Query is a technology used by .NET programming languages to perform queries on data. LINQ allows developers to query, filter and transform sets of data using native language syntax. One of the basic LINQ aggregation functions is Max, which finds and returns the maximum value in a result set of a query.

Instructions

    • 1

      Declare and initialize a collection or data source that implements the IEnumerable<T> interface. Any IEnumerable<T> source can be queried using LINQ.

      C# Example:

      int[] exampleArray = { 5, 8, 3, 12, 37, 22, 19 };

    • 2

      Use the Max operator to find the highest value in the data source. Max invokes a transformation operation on each element in the data source and then returns the highest result. To simply find the highest value in an array, Max can be used without any parameters.

      C# Example:

      int[] exampleArray = { 5, 8, 3, 12, 37, 22, 19 };

      //Returns 37

      int highest = exampleArray.Max();

    • 3

      Use a lambda expression to perform an operation on each element in the data source. A lambda expression is a type of anonymous function that is created using the "=>" lambda operator.

      C# Example:

      int[] exampleArray = { 5, 8, 3, 12, 37, 22, 19 };

      //Subtracts each element in the array by 50 and then finds the highest absolute value.

      //The element currently being processed is represented by the variable i, which is defined by the statement "i =>"

      //Returns 47, which is the result of Abs(3 - 50);

      int highest = exampleArray.Max(i => System.Math.Abs(i - 50));

Related Searches:

References

  • Photo Credit Jupiterimages/Photos.com/Getty Images

Comments

Related Ads

Featured