tags:

views:

64

answers:

3

So my database has a column which is a comma seperated list of category ID's, like:

"1,234,234,23,343,53"

My class will have a List property that will expose these ID's in a collection form.

If someone wants to add a CategoryID, they just do:

myList.Add(234);

BUT, when it is time to save to the database, I will have to convert the collection back to a comma seperated list.

What is the best way to do this? should I make the comma-seperated list of integers private?

+3  A: 

I would only allow access via one method. It's cleaner and prevents errors. So yes, make the list of integers private.

In fact, don't have a list of integers. Have a collection of integers and only convert them to a string when you write back to the database. If you must, override the collections .toString() method to provide the list of integers as a comma separated list. That was you can get your list easily, but people can't dick with it.

Dylan Lacey
+2  A: 

Something like this ought to do what you're looking for:

public class SomeClass
{
    public List<int> CategoryIDList { get; private set; }

    public void UpdateToDatabase()
    {
        string categoryIdList = ConvertIntListToString(this.CategoryIDList);
        // TODO Update Database.
    }

    private static string ConvertIntListToString(List<int> intList)
    {
        return string.Join(",", intList.Cast<string>().ToArray());
    }
}
Scott Ferguson
A: 

It really depends on the purpose of the class.

If the class is designed to hold the ID's only then you may want to look at inheriting from List and add methods for reading from the Database and saving to the database.

If the class contains more information than just the ID's then a private List is your best option.

Alastair Pitts