0

I know I've not gone about this in the easiest of manners but i'm fairly new to C#. I'm trying to make sure that when I select from only 1,2,3 or 4 of the 5 checked list boxes that i do not end up with the following

&& or &&& etc... I would like the final string to be xxxxx&xxxxx&xxx or similar as the String is added to a preset SQL query.

Code is below:

any help would be appreciated I've had a look around online for some help but not found much I was able to get my head round.

        List<object> list = checkedListBox1.CheckedItems.OfType<object>().ToList();
        List<object> list2 = checkedListBox2.CheckedItems.OfType<object>().ToList();
        List<object> list3 = checkedListBox3.CheckedItems.OfType<object>().ToList();
        List<object> list4 = checkedListBox4.CheckedItems.OfType<object>().ToList();
        List<object> list5 = checkedListBox5.CheckedItems.OfType<object>().ToList();


        string selected_fields_cb1 = string.Join(" ", list.ToArray());
        string selected_fields_cb2 = string.Join(" ", list2.ToArray());
        string selected_fields_cb3 = string.Join(" ", list3.ToArray());
        string selected_fields_cb4 = string.Join(" ", list4.ToArray());
        string selected_fields_cb5 = string.Join(" ", list5.ToArray());


        string allSelected = (selected_fields_cb1 + " " + selected_fields_cb2 + " " + selected_fields_cb3 +
           " " + selected_fields_cb4 + " " + selected_fields_cb5 + "");
        string allSelected2 = allSelected.Replace( " ", "&" );
        string allSelected3 = allSelected2.TrimEnd('&');
  • What is your ask ,can you please make it clear – TheGameiswar Oct 04 '16 at 07:22
  • @TheGameiswar sorry if i'm unclear, I'm looking for an effective way to make sure that the Final Edited string falls within certain parameters. those being. selected items from the checkedListboxes seperated by a single & and not && or &&& etc if i don't make a selection from all 5 is that clearer? – James Burnie Mcburnie Oct 04 '16 at 07:27

1 Answers1

0

If I understand well, you try to add spaces and then replace these spaces by &.

It would be easier to do this directly.

List<object> list = checkedListBox1.CheckedItems.OfType<object>().ToList();
List<object> list2 = checkedListBox2.CheckedItems.OfType<object>().ToList();
List<object> list3 = checkedListBox3.CheckedItems.OfType<object>().ToList();
List<object> list4 = checkedListBox4.CheckedItems.OfType<object>().ToList();
List<object> list5 = checkedListBox5.CheckedItems.OfType<object>().ToList();

var allObjects = list.Concat(list2).Concat(list3).Concat(list4).Concat(list5);
var res = string.Join("&", allObjects);
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122