Question

I have a property IList CategoryIDs, and a private string variable that contains a comma separated list, how to elegantly populate the IList collection?

I asked earler and I learn a neat way of populating the List with .AddRange(...), but now I realized I have to have the property return IList which doesn't seem to support the .AddRange method.

Was it helpful?

Solution

public IList CategoryIDs
{
    get
    {
        return list.Split(',')
                .ToList<string>()
                .ConvertAll<int>(new Converter<string, int>(s => int.Parse(s)));
    }
}

OTHER TIPS

// assignment
var ids = "1,2,3,4,5";
obj.CategoryIDs = ids.Split(',');
// or - if you want "add" capabilities
obj.CategoryIDs = new ArrayList(ids.Split(','));

// encapsulation
IList CategoryIDs 
{
    get { return ids.Split(','); }
}

Just create a new List, use the methods you need, and return the List. Since List implements IList, it will be valid for that property.

You can also just use add repeatedly:

var IDs = from s in commaSeparatedList.Split(',')
          select int.Parse(s);
foreach(var id in IDs)
    theIList.Add(id);

Try this:

public class Class1
{

    private String categoryIDList = "1,2,3";

    public Class1()
    {

        List<Int32> categoryList = new List<Int32>();

        String[] categoryIDs = categoryIDList.Split(",");

        foreach(String category in categoryIDs)
            categoryList.Add(Int32.Parse( category));

    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top