C# - Find the index of even numbers using LINQ

Learn, how to find the index of even numbers using Linq in C#? By Nidhi Last updated : April 01, 2023

Here we will find the index of even numbers using Linq Select() and Where() methods.

C# program to find the index of even numbers using LINQ

The source code to find the index of even numbers using Linq is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Find the index of even numbers using LINQ

using System;
using System.Collections.Generic;
using System.Linq;

class Demo {
  static void Main(string[] args) {
    List < int > intnums = new List < int > ();

    intnums.Add(10);
    intnums.Add(11);
    intnums.Add(12);
    intnums.Add(13);
    intnums.Add(14);

    var IndexOfEvenNumber = intnums.Select((num, index) => new {
        Numbers = num,
          IndexPosition = index
      }).Where(n => n.Numbers % 2 == 0)
      .Select(result => new {
        Number = result.Numbers,
          IndexPosition = result.IndexPosition
      });

    foreach(var value in IndexOfEvenNumber) {
      Console.WriteLine("Index:" + value.IndexPosition + " of Number: " + value.Number);
    }
  }
}

Output

Index:0 of Number: 10
Index:2 of Number: 12
Index:4 of Number: 14
Press any key to continue . . .

Explanation

In the above program, we created a list of integers. Then add the items to the List using Add() method.

var IndexOfEvenNumber = intnums.Select((num, index) => new {
	Numbers = num,
	  IndexPosition = index
  }).Where(n => n.Numbers % 2 == 0)
  .Select(result => new {
	Number = result.Numbers,
	  IndexPosition = result.IndexPosition
  });

In the above method, we find the index with selected even number and assigned the result to the variable "IndexOfEvenNumber".

foreach (var value in IndexOfEvenNumber)
{
    Console.WriteLine("Index:" + value.IndexPosition + " of Number: " + value.Number);
}

In the above code, we print the index with selected even numbers on the console screen.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.