选择具有相同ID的多个值

时间:2017-01-26 05:39:17

标签: c# asp.net

您好我不知道如何检索具有相同ID的所有值并将其显示在一个标签中。

示例:

id   food

1     chicken

1     fish

期望的输出

chicken,fish

我该怎么做?

SqlConnection con1 = new SqlConnection(strConnString);
con.Open();
str = "select food from foodName where id= 1";
com = new SqlCommand(str, con);

SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
    Label1.Text = reader["food"].ToString();
}
con.Close();

5 个答案:

答案 0 :(得分:0)

您可以使用StringBuilder

执行foreach并使用字符串添加表单
StringBuilder test = new StringBuilder();
foreach(yourClassname test in yourList)
{
    test.Append(test.name);
}

答案 1 :(得分:0)

在C#中使用lambda表达式。

 var list = new List<Product>(){
                new Product {ID=1, FoodName ="chicken"},
                new Product{ID=2, FoodName="egg"},
                new Product{ID=1, FoodName="fish"}
            };

 var output = list.Where(s => s.ID == 1).Select(s=>s.FoodName).ToArray(); //result will be array of items.

使用string.Join获取输出结果“chicken,fish”

string.Join(",", output); //result will be chicken,fish

答案 2 :(得分:0)

因为您无法向我们提供您的代码。我假设你有一份食物清单[List<Food>],你的内部有一个idfoodName。你能做的是:

IEnumerable<string> selectedFood = foods.FindAll(food => food.id == 1).Select(food => food.foodName);

string result = string.Join(", ", selectedFood);

您现在可以将结果用作标签的值。

希望这有帮助!

答案 3 :(得分:0)

如果您需要连接所有值:

String chickenVar = "Chicken";
String fishVar = "Fish";

 String result = chickenVar +", " + fishVar;

答案 4 :(得分:0)

Label1.Text = string.Empty;
SqlConnection con1 = new SqlConnection(strConnString);
con.Open();
str = "select food from foodName where id= 1";
com = new SqlCommand(str, con);

SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
    Label1.Text += reader["food"].ToString();
}
con.Close();
相关问题