Monday, August 2, 2010

Use Delegate to Delete an Item from a List

Iterating through the list items is quite a simple task when delegates are in place.

 
protected void GrvUploads_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.ToString() == "DeleNow")
        {
            List oUploader = Session["UploadedFiles"] as List;
            if (oUploader != null)
            {
                oUploader.Remove(oUploader.Find(delegate(UploadEntity oEntity)
                {
                    return (oEntity.UploadID == Convert.ToInt64(e.CommandArgument));
                }
                ));
            }
            Session["UploadedFiles"] = oUploader;
            BindUploadGrid();
        }
    }

1 comment:

AK Sabin said...

You can also use Lambda expression in 3.0 and upper version.

Int64 intUploadId = Convert.ToInt64(e.CommandArgument);
oUploader.Remove(oUploader.Find(o => o.UploadId == intUploadId));

Worth reading the following article,

.Net Collection Management in C#