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# program to 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.
Program:
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.
Output:
Explanation:
In the above program, we created a list of integers. Then add the items to the List using Add() method.
In the above method, we find the index with selected even number and assigned the result to the variable "IndexOfEvenNumber".
In the above code, we print the index with selected even numbers on the console screen.