Q:

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

belongs to collection: C# LINQ Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

//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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# LINQ Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to find string values from the list of ... >>
<< C# program to demonstrate the use of the method as...