C# LINQ Array of Integers


This entry is part 3 of 4 in the series C# LINQ

The book Illustrated C# 7, Fifth Edition by Daniel Solis and Cal Schrotenboer published by Apress has some example code using LINQ. Here we just have an array of integers. We filter that array with a Where() clause.

  • LINQ stands for Language Integrated Query and is pronounced “link.”
  • LINQ is an extension of the .NET Framework and allows you to query collections of data in a manner similar to using SQL to query databases.
  • With LINQ you can query data from databases, collections of objects, XML documents, and more.
using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqIntIllustrated
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 2, 12, 5, 15 }; // Data source
            IEnumerable<int> lowNums = // Define and store the query.
                  from n in numbers
                  where n < 10
                  select n;
            foreach (var x in lowNums) // Execute the query.
                Console.Write($"{ x }, ");
        }  // OUTPUT: 2, 5, 
    }
}

Notice that the query is first defined then executed. Note that there are entire books dedicated to LINQ in all of its subtleties.

Notice that we use the IEnumerable interface.

LINQ replacing a for Loop

We can reduce the following for loop with a LINQ statement. The objective here is to check each integer in an array against another integer to ensure that all integers within the array are less than or equal to the other integer. We use Max which is part of LINQ. For example, if the array had 2, 5 and 3, and the other number was 7 then we would return true because 7 is greater than or equal to all of the numbers in the array. The code below returns false.

int[] nums = { 1, 5, 3 };
int numbr = 4;
bool good = nums.Length == 0 ? true : numbr >= nums.Max();

good = true;
for (int i = 0; i < nums.Length; i++)
{
    if (nums[i] > numbr)
    {
        good = false;
        break;
    }
}

Below is another line of code that uses LINQ’s Distinct() to check if all of the characters in a string are the same or not.

[chharp]
str.Distinct().Count() == 1;
[/csharp]

Series Navigation<< C# LINQ Part 2C# LINQ Where >>