Using IList, how to populate it through a comma-separated list of identifiers

I have IDID ILID properties and a private string variable that contains a comma separated list, how to gracefully populate an IList collection?

I asked a mentor and I learned a neat way to populate a List with .AddRange (...), but now I realized that I should return an IList property that does not seem to support the .AddRange method.

+3
source share
5 answers
public IList CategoryIDs
{
    get
    {
        return list.Split(',')
                .ToList<string>()
                .ConvertAll<int>(new Converter<string, int>(s => int.Parse(s)));
    }
}
+9
source
// 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(','); }
}
+1

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

0
source

You can also just add a few times:

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

Try the following:

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

    }

}
0
source

Source: https://habr.com/ru/post/1719468/


All Articles