tags:

views:

32

answers:

3

My db column is a comma seperated list of category ID's.

I have a public property in my class that is:

List<int> CategoryIDs {get;set;}

I want to somehow lazy load this property, that when it is used, it will split the db column by its comma (its a comma seperated list of ids like: 1,2,343,2342).

It will then initialize a List.

+1  A: 

Do something like this:

List<int> categoryIds;

public List<int> CategoryIds
{
 get
 {
  if (this.categoryIds == null)
  {
   this.categoryIds = new List<int>();
   this.categoryIds.AddRange(
    getIds()
    .Split(',')
    .Select(s => Convert.ToInt32(s)));
  }
  return this.categoryIds;
 }
}

Where getIds is the function that returns the string of ids.

Andrew Hare
+1  A: 

Something like this?

private List<int> categoryIDs = null;
List<int> CategoryIDs
{
    get
    {
        if (categoryIDs == null)
        {
            categoryIDs = new List<int>();
            GetCategoryList().Split(',').ToList().ForEach(id => categoryIDs.Add(Convert.ToInt32(id)));
        }
        return(categoryIDs);
    }
    set
    {
        List<string> stringList = value.ConvertAll<string>(i => i.ToString());
        SetCategoryList(String.Join(",", stringList.ToArray()));
    }
}

public string GetCategoryList()
{
    throw new NotImplementedException();
}

public void SetCategoryList(string categoryList)
{
    throw new NotImplementedException();
}

Where GetCategoryList and SetCategoryList are the functions actually reading/updating the data on the database.

Badaro
A: 
private List<int> _CategoryIDs;

public IList<int> CategoryIDs
{
    get
    {
        if (_CategoryIDs == null)
        {
            _CategoryIDs = GetCommaSeparatedFieldFromDB()
                .Split(',')
                .Select(x => int.Parse(x))
                .ToList();
        }
        return _CategoryIDs;
    }
}
LukeH