In this post I write some examples of C# coding for SharePoint list items. These methods are rather fast and it's very actual for SharePoint.

It’s a method to return SPListItemCollection. I have extracted it just to easier modify code.

        public SPListItemCollection LoadDataTable()
        {
            SPWeb oWebsite = SPContext.Current.Web;
            SPList oList = oWebsite.Lists["corp_events"];
            SPQuery liQuery = new SPQuery();

            string query = @"
<ViewFields>
   <FieldRef Name='ID' />
   <FieldRef Name='Title' />
   <FieldRef Name='DatePlanned' />
   <FieldRef Name='DateFact' />
   <FieldRef Name='Company' />
</ViewFields>";
            liQuery.Query = query;
            SPListItemCollection myItems = oList.GetItems(liQuery);
            return myItems;
        }

 

I call up the method and get SPListItemCollection. After that I want to convert it to datatable. Don’t forget to add using System.Data to your code.

            SPListItemCollection myItems = LoadDataTable();
            DataTable dt = new DataTable();
            dt = (DataTable)  myItems.GetDataTable();

 

I have class CEvent

    public class CEvent
    {
        public string eventId { get; set; }
        public string title { get; set; }
        public string datePlan { get; set; }
        public string dateFact { get; set; }
        public string company { get; set; }
}

 

And want to convert my datatable to List<CEvent>. Here’s one of the ways to do it.

 

             List<CEvent> events = new List<CEvent>();

            events = (from DataRow row in dt.Rows
                      select new CorpEvent
                      {
                          eventId = row["ID"].ToString(),
                          title = row["Title"].ToString(),
                          datePlan = row["datePlan"].ToString(),
                          dateFact = row["dateFact"].ToString(),
                          company = row["company"].ToString()
                      }).ToList();