C# LINQ - Filtering List collection using Lambda expression

Program


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

namespace LinqSample
{
    class Player
    {
        public string playerName { get; set; }
        public long runs { get; set; }

        public Player()
        {
            playerName = "";
            runs = 0;
        }

        public Player(string pName,long rns)
        {
            playerName = pName;
            runs = rns;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Player> playersList = new List<Player>();

            Console.WriteLine("Enter the number of players");
            int NumOfPlayers = int.Parse(Console.ReadLine());

            for(int i=0;i<NumOfPlayers;i++)
            {
                Console.WriteLine("Enter player name");
                string pname = Console.ReadLine();

                Console.WriteLine("Enter run");
                int rns = int.Parse(Console.ReadLine());

                playersList.Add(new Player(pname, rns));
            }

                             //Here Where is LINQ Query function, p => p.runs >= 50 is lambda function

            var SelectedList = playersList.Where(p => p.runs >= 50);

            foreach(Player xP in SelectedList)
            {
                Console.WriteLine("{0}\t{1}", xP.playerName,                                                      xP.runs);
            }
            Console.ReadLine();
        }
    }
}

Output

Enter the number of players
4
Enter player name
Maxwell
Enter score
65
Enter player name
MS Dhoni
Enter score
77
Enter player name
Suresh Raina
Enter score
49
Enter player name
Ashwin
Enter score
14
Maxwell 65
MS Dhoni 77

No comments:

Post a Comment