Sunday, September 5, 2010

Evolution of data query in C#...

One of the most common operation in programming is data query. In C# 1.2, normally I would use a custom collection class that derived from System.Collections. But for sake of example here, I'll show it with an ArrayList instead.

Here's a class that'll become an element of the collection (yes, I know Auto-Implemented Properties).
    public class Student
{
private int _id;
private string _name;
private string _gender;

public Student()
{
}

public int Id
{
get { return _id; }
set { _id = value; }
}

public string Name
{
get { return _name; }
set { _name = value; }
}

public string Gender
{
get { return _gender; }
set { _gender = value; }
}
}
This is how I normally code in C# 1.2 (.NET Framework 1.1) with an ArrayList.
    private ArrayList SomeFilterMethod(ArrayList myList)
{
ArrayList result = new ArrayList();

for (int x = 0; x < myList.Count; x++)
{
if (((Student)myList[x]).Gender == "Male")
{
result.Add(myList[x]);
}
}

return result;
}
Generic list with action and predicate was introduced in C# 2.0 (.NET Framework 2.0). This is how my code will look like.
    private List<Student> SomeFilterMethod(List<Student> myList)
{
return mylist.FindAll(GetMaleStudents);
}

private bool GetMaleStudents(Student item)
{
return item.Gender == "Male";
}
Not to forget an anonymous methods.
    private List<Student> SomeFilterMethod(List<Student> myList)
{
return mylist.FindAll( delegate(Student item) { return item.Gender == "Male"; } );
}
In C# 3.0 (.NET Framework 3.5), there's LINQ with 2 flavours.
1) Lambda Expression
    private List<Student> SomeFilterMethod(List<Student> myList)
{
return mylist.FindAll( item => item.Gender == "Male" );
}
2) Query Expression
    private List<Student> SomeFilterMethod(List<Student> myList)
{
return (from student in mylist
where student.Gender == "Male"
select student).ToList<Student>();
}
Between the two, personally I prefer the former.

No comments:

Post a Comment