0

I have a checkedlistBox cblHobbies

StringBuilder hobbies = new StringBuilder(string.Empty);
foreach (ListItem li in cblHobbies.Items) {
    if (li.Selected) {
        hobbies.Append(li).Append(", ");
    }
}
string hobby = hobbies.ToString().TrimEnd(' ').TrimEnd(',');

I am storing hobby in SQL Server database as Varchar(MAX).

When the user edit his profile i want all the hobbies get selected already.

My Question is how to select checklistbox items from a comma separated list efficiently? (in respect of number of iterations)

5
  • 2
    Fyi, a nicer way: string hobby=String.Join(", ", cblHobbies.Items.Cast<ListItem>().Where(i=>i.Selected)); Commented Mar 1, 2016 at 14:38
  • 1
    But never store multiple informations in one value in your database. Instead store every selected item in it's own record. So this comma separated string does not belong in the database. Commented Mar 1, 2016 at 14:41
  • Thanks @Tim :) i will use that. But i can't change DB now. Commented Mar 1, 2016 at 14:42
  • However, aren't you mirco optimizing things? What are you trying to optimize at all? If you have read the value from database you can use a simple loop to select them. It's extremely efficient. Commented Mar 1, 2016 at 14:46
  • Ok well i thought it can't be optimized much as well. No worries. Thanks @Tim. But i am having trouble deducing code for selecting it from text without using if else. Commented Mar 1, 2016 at 14:51

1 Answer 1

3

Summarizing my comments:

  • You can use following readable one-liner instead of your StringBuilder-loop:

    string hobby = String.Join(", ", cblHobbies.Items.Cast<ListItem>()
                                               .Where(i=> i.Selected));
    
  • Never store multiple informations in one value in your database. Instead store every selected item in it's own record. So this comma separated string does not belong there. Normalize your Database.

    • That's much more efficient
    • allows easier queries
    • avoids corrupt data
    • etc. ...

However, aren't you mirco optimizing things? If you have read the value from database you can use a simple loop to select them. It's very efficient.

string hobby = GetHobbyFromDB();
string[] hobbies = hobby.Split(new []{", "}, StringSplitOptions.None);

foreach (ListItem li in cblHobbies.Items)
    li.Selected = hobbies.Contains(li.Text);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.