与凡根据列表值在asp.net条件选择查询 [英] Select Query with Where condition depending on list values in asp.net

查看:110
本文介绍了与凡根据列表值在asp.net条件选择查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SQL表。我也已经列表在我的Asp.Net code(C#)。

I've an sql table. I've also a list in my Asp.Net code (C#).

public static List listColumns = new List();

和listColumns包含1,2,3 ...... 10只。例如,它可以包含1,5,6,9,我想使此条件的查询。所以,如果列表这些价值观,我的查询应该是:

And listColumns contains 1,2,3...10 randomly. For example it can contains 1, 5, 6, 9. I want to make a query with this conditions. So, If the list has these values, my query should be:

SELECT * FROM Table WHERE id=1 or id=5 or id=6 or id=9

该listColumns可能包含不同的值,并有不同的计数。我怎么能定期做查询?

The listColumns may contains different values and has different counts. How can I do this query regularly?

推荐答案

下面是一个没有循环的解决方案,但不幸的是还没有一个参数化的SQL语句:

Here is a solution without a for loop, but unfortunately also without a parameterized SQL statement:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

public class test {
  public static void Main(string[] args)
  {
    //List<int> listColumns = new List<int>(){ 1, 5, 6, 9};
    System.Collections.Generic.List<int> listColumns = new System.Collections.Generic.List<int>(){ 1, 5, 6, 9};
    string s = String.Join(", ", listColumns.Select(x => x.ToString()));

    string sql = String.Format("SELECT * FROM Table WHERE ID IN ({0})", s);
    Console.WriteLine(sql);
  }
}

请注意,使用 SELECT * 被认为是不好的做法

Please note that using select * is considered as a bad practice

修改下面是一些新的code,因为你的列表是类型 System.Web.UI.MobileControls.List

edit Here is some new code because your list is of type System.Web.UI.MobileControls.List

string sql = String.Format("SELECT * FROM Table WHERE ID IN ({0})", 
                 listColumns.ListItem.Value);

编辑2 我已经采取了code从您的评论:

edit 2 I have taken the code from your comment:

list.Items.Clear(); 
string values = DropDownList4.SelectedValue; 
string[] words = values.Split(','); 

foreach (string s in words) 
    if (s != "" && s != string.Empty && s != null)     
        list.Items.Add(s);

我想你有这样的下拉更改事件还是什么?和你的下拉有像值1,5,6,9的字符串。
如果所有我的假设是正确的,你可以使用:

I guess that you have this on the dropdown changed event or something? and your dropdown has a string like "1,5,6,9" in the value. If all my assumptions are correct you can use:

System.Collections.Generic.List<int> selectedValues = new     System.Collections.Generic.List<int>();

foreach (string s in words)
    if (!String.IsNullOrWhiteSpace(s))
        selectedValues.Add(Convert.ToInt32(s));
string ids = String.Join(", ", selectedValues.Select(x => x.ToString()));
string sql = String.Format("SELECT * FROM Table WHERE ID IN ({0})", ids);

这篇关于与凡根据列表值在asp.net条件选择查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆