+92 332 4229 857 99ProjectIdeas@Gmail.com

Applying LINQ On Class Part 1 (C#.net)



Applying LINQ on class part 1 (C#.net):
In the following code applying a queries on user defined class. A Player class contains name of person and the score list. See the code below.


Code

public class Player
        {
            public string Name { get; set; }
            public List<int> Scores { get; set; }
        }

// Creating playersList and adding Player objects in the list
public List<Player> playersList = new List<Player>
        {
            new Player {
                Name = "Shahid Afridi",
                Scores = new List<int>{56,67,07}
            },
            new Player {
                Name = "Umar Akmal",
                Scores = new List<int>{100,150,100}
            },
            new Player {
                Name = "Saeed Anwar",
                Scores = new List<int>{144,148,203}
            },
            new Player {
                Name = "Michael Clarke",
                Scores = new List<int>{158,167,144}
            },
            new Player {
                Name = "Imran Khan",
                Scores = new List<int>{188,173,189}
            }
        };

// Query 1 : The following players have score average over 160
var query1 =
        from Player p in playersList
        where(p.Scores.Average() > 160)
        select p;

foreach (Player p in query1)
       Console.WriteLine("Name: " + p.Name + " : Average Score: " + p.Scores.Average());

Output:

Name: Saeed Anwar : Average Score : 165
Name: Imran Khan : Average Score : 183.3


// Query 2 : The following players have scores over 200
var query2 =
        from Player p in playersList
        where (p.Scores.Max() > 200)
        select p;

foreach (Player over200Group in query2)
       Console.WriteLine(over200Group.Name + " : " + over200Group.Scores.Max());

Output:
Name: Saeed Anwar : 203

 // Query 3 : Selecting those players whose name starts with “S”
var query3 =
       from Player p2 in playersList
       where p2.Name.StartsWith("S")
       select p2;

foreach (Player p in query3)
       Console.WriteLine(p.Name + " : " + p.Scores.Sum());

Output:

Name: Saeed Anwar : 495
Name: Shahid Afridi : 130


see this in vb.net

0 comments: