tags:

views:

243

answers:

5

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.

A: 

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.

Matt
+9  A: 
public IList CategoryIDs
{
    get
    {
        return list.Split(new char[]{','})
                .ToList<string>()
                .ConvertAll<int>(new Converter<string, int>(s => int.Parse(s)));
    }
}
najmeddine
+1 for a one-liner solution
Chris Ballance
But I need IList<int> not strings, so .ToList<string>(); won't work?
mrblah
Done. I edited my answer.
najmeddine
A: 
// 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(','); }
}
Travis Heseman
A: 

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);
Reed Copsey
A: 

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));

    }

}
Joe Sweeney