Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Find the Index of Even Numbers using LINQ

  • Last Updated : 28 Nov, 2021

Given an array, now our task is to find the index value of the even numbers present in the given array using LINQ. LINQ is known as Language Integrated Query and was introduced in .NET 3.5. It gives the power to .NET languages to generate queries to retrieve data from the data source. So to do this task we use the select() and where() methods of LINQ.

Example:

Input  : { 2, 3, 4, 5, 11 }
Output : Index:0 - Number: 2
         Index:2 - Number: 4
         
Input  : { 2, 3, 4, 5, 6, 23, 31 }
Output : Index:0 - Number: 2
         Index:2 - Number: 4
         Index:4 - Number: 6

Approach:

1. Create a list of integer type and add elements to it.

2. Get the index of the numbers present in the list.

var indexdata = data.Select((val, indexvalue) => new
                    { 
                        Data = val, 
                        IndexPosition = indexvalue
                    }).Where(n => n.Data % 2 == 0).Select(
                    result => new 
                    { 
                        Number = result.Data,
                        IndexPosition = result.IndexPosition 
                    });

3. Display the index and numbers.

foreach (var i in indexdata)
{
    Console.WriteLine("Index:" + i.IndexPosition + 
                      " - Number: " + i.Number);
}

Example:

C#




// C# program to find the index value of
// the even numbers using LINQ
using System;
using System.Collections.Generic;
using System.Linq;
  
class GfG{
      
static void Main(string[] args)
{
      
    // Creating a list of integer type
    List<int> data = new List<int>();
      
    // Add elements to the list
    data.Add(2);
    data.Add(3);
    data.Add(4);
    data.Add(5);
    data.Add(6);
    data.Add(12);
    data.Add(11);
  
    // Get the index of numbers
    var indexdata = data.Select((val, indexvalue) => new
                    
                        Data = val, 
                        IndexPosition = indexvalue
                    }).Where(n => n.Data % 2 == 0).Select(
                    result => new 
                    
                        Number = result.Data,
                        IndexPosition = result.IndexPosition 
                    });
                      
    // Display the index and numbers
    // of the even numbers from the array
    foreach(var i in indexdata)
    {
        Console.WriteLine("Index Value:" + i.IndexPosition + 
                          " - Even Number: " + i.Number);
    }
}
}

Output:

Index Value:0 - Even Number: 2
Index Value:2 - Even Number: 4
Index Value:4 - Even Number: 6
Index Value:5 - Even Number: 12


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!