Simple Queries

Simple queries

We shall use this data source to see some queries

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Mark { get; set; }
    public string City { get; set; }
}

Student[] studentList =
{
    new Student() { StudentID = 1, StudentName = "John Nigel", Mark = 73, City ="NYC"} ,
    new Student() { StudentID = 2, StudentName = "Alex Roma",  Mark = 51 , City ="CA"} ,
    new Student() { StudentID = 3, StudentName = "Noha Shamil",  Mark = 88 , City ="CA"} ,
    new Student() { StudentID = 4, StudentName = "James Palatte" , Mark = 60, City ="NYC"} ,
    new Student() { StudentID = 5, StudentName = "Ron Jenova" , Mark = 85 , City ="NYC"}
};

Display Name and Mark of students with Mark higher than 80:

var toppers = from student in studentList
                where student.Mark > 80
                select student;

foreach (var s in toppers)
Console.WriteLine(s.StudentName + " " + s.Mark);

Console.ReadKey();

Try the same in method syntax

Display Name and Cityof students from NYC with Mark higher than 70:

var res = studentList.Where(s=>s.Mark >70 && s.City =="NYC");

foreach (var s in res)
    Console.WriteLine(s.StudentName + " " + s.City);

Console.ReadKey();

How many have score 70 and above?

var res = studentList.Where(s=>s.Mark >70 && s.City =="NYC").Count();

Console.WriteLine(res);

Console.ReadKey();

What is the name of student with ID number 4?

var res = studentList.Single(s => s.StudentID == 4);

Console.WriteLine(res.StudentName);

Console.ReadKey();

Display the name of the first student who has scored less than 60

var res1 = studentList.First(s=>s.Mark<60);
Console.WriteLine(res1.StudentName);

//or

var res2 = studentList.Where(s => s.Mark < 60).First();
Console.WriteLine(res2.StudentName);

Console.ReadKey();

Try to find who is the last student from the city "CA”?

Last updated