Jun
28
2007
.NET generics collection and removeall
Posted by admin under
.NET 2.0
I am getting more and more used to generics and must say I just love the anonymous methods. Here we will use the RemoveAll function to remove objects not to be published (Publishdate > now)
public class MyObj
{
public MyObj(string sName, DateTime dtPubDate)
{
Name = sName;
PublishDate = dtPubDate;
}
public string Name;
public DateTime PublishDate;
}
public class MyObjList : List<MyObj>
{
}
That's the simple object model we are dealing with. Now lets fill it
MyObjList oList = new MyObjList();
oList.Add( new MyObj("Hello", new DateTime(2000,1,1,0,0,0)) );
oList.Add(new MyObj("Future", new DateTime(2010, 1, 1, 0, 0, 0)));
oList.Add(new MyObj("Now", DateTime.Now));
and now call RemoveAll
EEEContent_3
We are supposed to return true for each object to be removed. It so neat to be able to specify the method inlinde, but we could also put it inside the collection:
public class MyObj
{
public MyObj(string sName, DateTime dtPubDate)
{
Name = sName;
PublishDate = dtPubDate;
}
public string Name;
public DateTime PublishDate;
}
public class MyObjList : List<MyObj>
{
public void RemoveFuture()
{
RemoveAll(delegate(MyObj oObj)
{
return oObj.PublishDate > DateTime.Now;
});
}
}
...
MyObjList oList = new MyObjList();
oList.Add( new MyObj("Hello", new DateTime(2000,1,1,0,0,0)) );
oList.Add(new MyObj("Future", new DateTime(2010, 1, 1, 0, 0, 0)));
oList.Add(new MyObj("Now", DateTime.Now));
oList.RemoveFuture();