C# Program to Find the Index of Even Numbers using LINQ
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#
using System;
using System.Collections.Generic;
using System.Linq;
class GfG{
static void Main( string [] args)
{
List< int > data = new List< int >();
data.Add(2);
data.Add(3);
data.Add(4);
data.Add(5);
data.Add(6);
data.Add(12);
data.Add(11);
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
});
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
Last Updated :
28 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...