0

I've ran into some trouble with string manipulation with arrays.

I have this:

public string LB_Ward_Selected()
{
    string SelectedWard = String.Join(",", LB_Ward.Items.Cast<ListItem>()
                                               .Where(i => i.Selected));
    string[] SelectedItems = SelectedWard.Split(',');
    for (int i = 0; i < SelectedItems.Length; i++)
    {
        SelectedItems[i].Replace(SelectedItems[i].ToString(), "'" + SelectedItems[i].ToString() + "'").ToArray();
    }
    SelectedWard = string.Join(",", SelectedItems);
    return SelectedWard;
}

I taking a multiple selection from an asp listbox which I collate as a CSV string, then split into an array then try to change (using Replace.) the separated strings in the array then output it back into a comma separated value string.

I can't see why it isn't working, any ideas?

HTML:

<asp:ListBox ID="LB_Ward" runat="server" DataSourceID="SQLWard" CssClass="btn btn-default" SelectionMode="Multiple"
    DataTextField="WARD" DataValueField="WARD" AutoPostBack="True" AppendDataBoundItems="true" EnableViewState="false" OnSelectedIndexChanged="DD_area_SelectedIndexChanged">
    <asp:ListItem Value="0">Select Ward</asp:ListItem>
</asp:ListBox>

<asp:SqlDataSource ID="SQLWard" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>"
    SelectCommand="SELECT DISTINCT [WARD]  FROM [Borough] WHERE Borough =@BoroughFilter">

    <SelectParameters>
        <asp:ControlParameter ControlID="DropDownListBorough" PropertyName="SelectedValue"
            Name="BoroughFilter" Type="String" DefaultValue="" />
    </SelectParameters>
</asp:SqlDataSource>

The method is called like this:

if (LB_Ward.SelectedIndex > 0)
{
    ward = LB_Ward_Selected();
}

Which I know requires refining! :)

1
  • The usual convention for local variables is starting with a lowercase letter. Commented Jan 30, 2015 at 13:11

2 Answers 2

3

You are doing nothing with the output of the Replace method:

SelectedItems[i] = SelectedItems[i].Replace(...)

You need to do this since string instances can't be manipulated, there are immutable. The only way to 'change' them is to set their instance to another one.

Also, there is no point in calling SelectedItems[i].ToString(), since SelectedItems[i] is a string already.

Sign up to request clarification or add additional context in comments.

4 Comments

So; SelectedItems[i] = SelectedItems[i].Replace(SelectedItems[i], "'" + SelectedItems[i] + "'").ToArray(); Doing this gives an error 'Cannot implicity convert type 'char[]' to string. Am i being simple?
Don't call .ToArray().
Yeah being SImple then (it is a friday!) Thanks for your help.
@MikeHughes Since all you're doing is adding single quotes around the string you could just do SelectedItems[i] = "'" + SelectedItems[i] + "'";
1

The main issue with your code is that you are not assigning the return value of Replace back to the array. But your entire code can be simplified to the following:

return string.Join(
    ",", 
    LB_Ward.Items
        .Cast<ListItem>()
        .Where(i => i.Selected)
        .Select(i => "'" + i.ToString() + "'")
        .ToArray());

This gets all the items that are selected, puts single quotes around them, and then joins them together with a comma separator. This avoids the joining, splitting and then rejoining that your code currently does along with the unnecessary use of Replace.

Note: You can even remove the ToString in the Select, I just put it there to make it clear how the ListItem is being turned into a string.

The only possible caveat here is if any of your items have commas in there text. If that is the case then your original code is actually splitting individual items up and the code above would not result in the same output. To accomplish that you can do the following.

return string.Join(
    ",", 
    LB_Ward.Items
        .Cast<ListItem>()
        .Where(i => i.Selected)
        .SelectMany(i => i.ToString().Split(',').Select(s => "'" + s + "'"))
        .ToArray());

The difference here is that we attempt to split each item on commas, take the results and put single quotes around them and then use SelectMany to flatten out the multiple resulting enumerations into one.

Note: In this case the ToString is required to be able to do the Split.

1 Comment

That is brilliant thank you for taking the time to show and explain this.

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.