BaseGenericCollection<Student> _students = LoadStudents();//Load up a Generic collection of Student objects
//Use a Linq expression to sort the students
var students = from student in _students orderby student.Major select student;
//The Students are ordered using the Linq expression above
foreach (var student in students)
{
Console.WriteLine("{0,-10} \t{1,-10} \t{2,-10} \t{3,-10:d} \t{4,-10:D} ", student.FirstName,
student.LastName, student.Major, student.EnrollmentDate, student.GraduationDate);
}
//First define the major we are looking for
Program._majorToFind = "Physics";
//Use a Linq expression to find the students with the desired major
var studentsWithMajor = from student in _students where student.Major == Program._majorToFind select student;
//Now we can loop thru the collection returned from using a Linq expression to query the Generic collection
foreach (var student in studentsWithMajor)
{
Console.WriteLine("{0,-10} \t{1,-10} \t{2,-10} \t{3,-10:d} \t{4,-10:D} ", student.FirstName,
student.LastName, student.Major, student.EnrollmentDate, student.GraduationDate);
}
//Now we can loop thru the collection returned by the "FindByLastName" methods
Program._lastNameToFind = "Valenti";
//Use a Linq expression to find the student with the desired last name
Student studentToFind = (from student in _students
where student.LastName == Program._lastNameToFind
select student).ToList<Student>()[0];
Console.WriteLine("{0,-10} \t{1,-10} \t{2,-10} \t{3,-10:d} \t{4,-10:D} ", studentToFind.FirstName, studentToFind.LastName, studentToFind.Major, studentToFind.EnrollmentDate, studentToFind.GraduationDate);
The ordering lambda expression from Part 2 (_students.OrderBy(student => student.Major)) is replaced with a Linq expression. The Linq expression is also type safe and provides a different syntax for sorting thru a Generic collection. The Find and FindAll methods have also be replaced with Linq expressions. Notice that the Linq expression that looks for a last name. The entire expression is cast to a List<Student> and the zeroth element is returned. This allows for immediate execution so we don’t have to use a foreach loop to retrieve the instance(s).
Linq, like lambda expressions, can reduce the amount of code that legacy strongly typed collection classes would normally have. Business requirements inevitably change and Low maintenance of middle tier objects is desired. Linq is extensible and provides flexibility in its uses such that the code can be slightly modified to search over a dataset instead of a strongly typed collection or many other storage mechanisms. This flexibility can reduce maintenance and can lower the amount of code in data tiers by reducing the logic needed to determine the correct persistent store.