LINQ - Handling Legacy Code
LINQ is for queries, no doubt about it. Yet - we can do some interesting thins with LINQ, and not just queries. For example, we all deal sometimes with legacy code inherited from some old project - so here some interesting ways to handle this code with few simple lambda expressions.
For this example, I will use this Employee class:
public class Employee
{
public Employee(string firstName)
{
this._firstName = firstName;
}
private int _id;
private string _firstName;
private string _lastName;
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public int ID
{
get { return _id; }
set { _id = value; }
}
}
Creating Collections
Lets say we have an array of strings returned from database, represents the employees names:
string [] users = {"Gilad", "Maor", "Michal", "Shachar", "Gili"};
Now, we want to create an Array with an Employee class for each user in the "users" array.
Employee[] arrUsers = users.Select(e => new Employee(e)).ToArray();
How simple is that?
Lets go further, say we want to create a generic List<Employee> from the "users" array:
List<Employee> employees = users.Select(e => new Employee(e)).ToList();
We can also do the same on integers Array:
string [] arrNumbers = {"5", "3", "8", "10"};
int [] arrIntegers = arrNumbers.Select(i => int.Parse(i)).ToArray();
Sorting the integers array is simple as that:
int [] arrIntegers = arrNumbers.Select(i => int.Parse(i)).OrderBy(i => i).ToArray();
How about Casting?
Lets assume that we already have an ArrayList contains Employee objects in it.
public ArrayList GetEmployees()
{
ArrayList list = new ArrayList();
list.Add(new Employee("gilad 1"));
list.Add(new Employee("gilad 2"));
list.Add(null);
list.Add(new Object());
return list;
}
ArrayList arrEmployees = GetEmployees();
Now we want to create a generic List<Employee> from that Arraylist, we can do that easily with casting the objects in the ArrayList to Employee classes.
List<Employee> employees = arrEmployees.Cast<Employee>().ToList();
But, the problem here as you may notice, is that one of the objects in the ArrayList is null and another one is not even an Employee class.
In this case, we will get an InvalidCastException when we try to cast the NULL value to Employee class, and the same goes to the Object().
This can happen sometimes in legacy code, and the solution for that is simple:
List<Employee> employees = arrEmployees.OfType<Employee>().ToList();
The different between Cast<> and OfType<> is that Cast<> throws an InvalidCastException on every type that doesn't match specific casting type, while OfType will cast only if its the same casting type.
Conclusion
Yes, LINQ is for querying , but you can use it for more operation except that.
Work against the legacy code object is easier, more abstract and understandable.
Related Links
The LINQ Project
www.LINQDev.com
Introduction to LINQ
Pro LINQ