Andy Jackson Andy Jackson - 2 months ago 6
C# Question

Adding to a constructor class

I'm stumped. I have a constructor class that looks like so:

class CClasses
{
public class CCategoryGroup : List<CCategory>
{
public string CTitle { set; get; }
public string CShortTitle { set; get; }
public CARESCategoryGroup(string ctitle, string cshorttitle)
{
this.CTitle = ctitle;
this.CShortTitle = cshorttitle;
}
};

public class CCategory
{
public int CID { set; get; }
public string CName { set; get; }
public ImageSource CIcon { set; get; }
public string CUrl { set; get; }
public CCategory(int cid, string cname, ImageSource cicon, string curl)
{
this.CID = cid;
this.CName = cname;
this.CIcon = cicon;
this.CUrl = curl;
}
};
}


I want to add to the constructor portion of the class like so:

//List<CCategoryGroup> ccategory = new List<CCategoryGroup>
//{
// new CCategoryGroup("Dolphin", "Dolphin Group")
// {
// new CCategory(1, "Bear", ImageSource.FromFile("bear.png")),
// new CCategory(2, "Elephant", ImageSource.FromFile("elephant.png")),
// new CCategory(3, "Dog", ImageSource.FromFile("dog.png")),
// new CCategory(4, "Cat", ImageSource.FromFile("cat.png")),
// new CCategory(5, "Squirrel", ImageSource.FromFile("squirrel.png"))
// },


My problem is I'm trying to add to this class through a loop. So I'm easily able to add the CCategoryGroup with:

cCategory.Add(new CCategoryGroup(name, value)


How do I add to the CCategory constructor as shown previously?

foreach (XElement catelement in xmlDoc.Descendants(xmlNS + "Category"))
{

cCategory.Add(new CCategoryGroup(catelement.Element(xmlNS + "Name").Value, catelement.Element(xmlNS + "Name").Value){
foreach (XElement subcatelement in xmlDoc.Descendants(xmlNS + "SubCategory"))
{
i++;

new CCategory(i, subcatelement.Element(xmlNS + "Name").Value, "", subcatelement.Element(xmlNS + "URL").Value);
}
});
}


I'm parsing XML and trying to add the results to the class. This does not work, obviously. But is a sample of what I'm trying to do. The first ".add" to cCategoryGroup works great, its the constructor CCategory I cannot add too the way I did in the commented out code.

Answer

No, you can't use a loop within the collection initializer like that, but you can do it without an initializer:

foreach (XElement catelement in xmlDoc.Descendants(xmlNS + "Category"))
{

    CCategoryGroup categoryGroup = new CCategoryGroup(catelement.Element(xmlNS + "Name").Value, catelement.Element(xmlNS + "Name").Value;
    cCategory.Add(categoryGroup);

    foreach (XElement subcatelement in xmlDoc.Descendants(xmlNS + "SubCategory"))
    {
        i++;
        categoryGroup.Add(new CCCategory(i, subcatelement.Element(xmlNS + "Name").Value, "", subcatelement.Element(xmlNS + "URL").Value));
    }
}

Note that an initializer just gets translated to a series of Add calls by the compiler, so functionally there's no difference between that and adding in a loop.