質問

I'm trying to build a SQL query using StringBuilder and I've become stuck trying to do part of the WHERE clause.

I have a list box with a bunch of values and allows multiple selection. I need to iterate through the selected items and put then in an IN statement like...

WHERE SOME_FIELD IN ('Value','NextValue','AnotherValue')

so far I've written the code like this...

if (lstSalesGroup.SelectedItem != null)
{
    selectQuery.Append("AND SALES_GROUP IN (");
    foreach (ListItem item in lstSalesGroup.Items)
    {
        if (item.Selected)
            selectQuery.Append("'" + item.Value + "',");
    }
    selectQuery.Append(")");
}

I need to test if the item is the last in the loop so that it doesn't put on the "," before the closing ")".

How can I do this? Or if there's a better way to build this part of the query please do suggest, I am still learning, we all have to start somewhere! :)

Eventually this will be a query for a part search.

Thanks in advance

役に立ちましたか?

解決

Couple of ways for doing that.

You can use string.TrimEnd to remove the extra comma from the string or you can create a new string using string.Join like

string InPartQuery = string.Join(",", lstSalesGroup.Items
                                          .Cast<ListItem>()
                                          .Where(t => t.Selected)
                                          .Select(r => "'" + r.Value + "'"));

他のヒント

You could use String.Join with some Linq

For clearity I've put the code in variables.

if (lstSalesGroup.SelectedItem != null)
{
    var queryStr = "AND SALES_GROUP IN ({0})";
    var selectedItemValues = (from itm in lstSalesGroup.Items.Cast<ListItem>()
                              where itm.Selected
                              select String.Format("'{0}'", itm));
    selectQuery.Append(String.Format(queryStr, String.Join(",", selectedItemValues)));
}

Try using linq

selectQuery.Append("AND SALES_GROUP IN (");

selectQuery.Append(string.Join(",", lstSalesGroup.Items.Select(i => "'" + i.Value + "'")));    

selectQuery.Append(")");

This will solve your problem, but you have a problem with SQL injection here. I would strongly advice you to use parameters in your query.

Dim s As String = "'"
    For i = 0 To ListBox1.Items.Count - 1
        s = s & ListBox1.Items.Item(i) & "','"
    Next

Try this:

if (lstSalesGroup.SelectedItem != null)
{
    selectQuery.Append("AND SALES_GROUP IN (");
    var local = lstSalesGroup.Items.Where(c => c.Selected)
                       .Select(c => "'"+c.Value+"'")
                       .Aggregate((c,n) => c+ ", "+n);

   selectQuery.Append(local);            
   selectQuery.Append(")");
}

Look at this example for more info on the .Aggragate(...) method

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top