Here's a class that'll become an element of the collection (yes, I know Auto-Implemented Properties).
public class StudentThis is how I normally code in C# 1.2 (.NET Framework 1.1) with an ArrayList.
{
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; }
}
}
private ArrayList SomeFilterMethod(ArrayList myList)Generic list with action and predicate was introduced in C# 2.0 (.NET Framework 2.0). This is how my code will look like.
{
ArrayList result = new ArrayList();
for (int x = 0; x < myList.Count; x++)
{
if (((Student)myList[x]).Gender == "Male")
{
result.Add(myList[x]);
}
}
return result;
}
private List<Student> SomeFilterMethod(List<Student> myList)Not to forget an anonymous methods.
{
return mylist.FindAll(GetMaleStudents);
}
private bool GetMaleStudents(Student item)
{
return item.Gender == "Male";
}
private List<Student> SomeFilterMethod(List<Student> myList)In C# 3.0 (.NET Framework 3.5), there's LINQ with 2 flavours.
{
return mylist.FindAll( delegate(Student item) { return item.Gender == "Male"; } );
}
1) Lambda Expression
private List<Student> SomeFilterMethod(List<Student> myList)2) Query Expression
{
return mylist.FindAll( item => item.Gender == "Male" );
}
private List<Student> SomeFilterMethod(List<Student> myList)Between the two, personally I prefer the former.
{
return (from student in mylist
where student.Gender == "Male"
select student).ToList<Student>();
}
No comments:
Post a Comment