Sunday, July 21, 2013

Single Key with multiple Values in C#

This a simple assumption work around to find the solution for how to retrieve the multiple values through Single Key. NamedValueCollection class in linq comes in handy for me. Helpful link from MSDN NameValueCollection This was very useful when an Library list having many books authored by different authors Just consider a situation you wanted to send an email notification to each individual authors the ratings received from the readers.For this aggregate all of his book details. You need to group the books by grouping authors.Assumption book details from the MSDN. Download from here Book.xml On click of the Button "ReadXmlRecord" method will be called.Read the XML file as DataTable and iterate all the rows with your entity class to apply NameValueCollection for further sorting and filtering. After grouping the record in SharePoint List.

    public void ReadXmlRecord(object sender, EventArgs e)
        {
            BookWithAuthor objBook = null;
            DataSet ds = new DataSet();
            ds.ReadXml(@"D:\books.xml");
            var BookTab = ds.Tables[0];
            NameValueCollection values = new NameValueCollection();
            foreach (DataRow row in BookTab.Rows)
            {
                objBook  = new BookWithAuthor();
                objBook.Author = row["author"].ToString();
                objBook BookTitle = row["title"].ToString();
                cols.Add(objBook.Author, objBook.BookTitle);
                
            }
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    foreach (String value in values.AllKeys)
                    {
                        SPList list = web.Lists["SiteReminder"];
                        SPListItem item = list.Items.Add();
                        web.AllowUnsafeUpdates = true;
                        item["SiteOwner"] = value;
                        item["SiteDetails"] = values[value];
                        item.Update();
                        web.AllowUnsafeUpdates = true;
                    }
                }
            }
            
        }
Class
public class BookWithAuthor
    {
        public string Author { get; set; }
        public string BookTitle { get; set; }
    }
Before grouping the record in Gridview,