字符串汇总来自sql

时间:2013-11-22 15:36:00

标签: c# sql sql-server

我有一个包含大量电子邮件地址的数据库,我需要将它们格式化为一个字符串,如下所示:

toaddress = "name@gmail.com,name1@gmail.com,name2@gmail.com,name3@gmail.com"

当前代码:

string toaddress = "";
using (SqlConnection conn = new SqlConnection(""))
{
    SqlCommand cmd = new SqlCommand("SELECT email FROM dbo.Members", conn);
    conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        toaddress = rdr["email"].ToString();
    }
    rdr.Close();
}

6 个答案:

答案 0 :(得分:5)

最简单的方法是使用StringBuilder之类的

StringBuilder sb = new StringBuilder();
string toaddress = null;
using (SqlConnection conn = new SqlConnection(""))
{
    SqlCommand cmd = new SqlCommand("SELECT email FROM dbo.Members", conn);
    conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        sb.Append(rdr["email"].ToString() + ",");
    }
    rdr.Close();
}

toaddress = sb.ToString().TrimEnd(',');

请记住使用Trim

从字符串末尾, String.TrimEnd开始

如果您在usingCommand对象上使用DataReader语句会更好,例如:

using (SqlConnection conn = new SqlConnection(""))
{
    using (SqlCommand cmd = new SqlCommand("SELECT email FROM dbo.Members", conn))
    {
        conn.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                sb.Append(rdr["email"].ToString() + ",");
            }
        }
    }
}

答案 1 :(得分:3)

将地址切换为List<string>,如下所示:

List<string> addresses = new List<string>();

获得时使用add

addresses.Add(rdr["email"] as string));

然后在最后使用string.Join

var toaddress = string.Join(",", addresses);

*编辑*

建议二,避免迭代两次:

public IEnumerable<string> GetEmails()
{
  using (SqlConnection conn = new SqlConnection(""))
  {
      SqlCommand cmd = new SqlCommand("SELECT email FROM dbo.Members", conn);
      conn.Open();
      SqlDataReader rdr = cmd.ExecuteReader();
      while (rdr.Read())
      {
          toaddress = rdr["email"].ToString();
      }
      rdr.Close();
  }
}

然后只需致电:string.Join(",", GetEmails())

这样一来,如果你想用它做疯狂的东西,你可以,la:

string.Join(",", GetEmails().Select(email => email.ToLower()).Distinct())

使所有电子邮件小写且不同(例如)。

答案 2 :(得分:1)

使用Sql Server(2008肯定,似乎是在2005年,但不确定),您可以使用FOR XML将所有行连接为','作为分隔符和STUFF以删除第一个',':

select stuff((select ',' +email 
              from Members
              for XML PATH('')),1,1,'')

答案 3 :(得分:0)

你正在覆盖当前的字符串。为了使它工作,你需要像

一样追加它
toaddress += "," + rdr["email"].ToString();

然而,这是一种丑陋的方式。你最好先把结果放在List中并使用string.Join

List<string> addresses = new List<string>();
... database stuff    
while (rdr.Read())
{
  addresses.Add(rdr["email"].ToString());
}
... stuff
string toaddress = string.Join(",", addresses)

答案 4 :(得分:0)

您可以制作List并使用string.Join将这些项目组合在一起。

List<string> items = new List<string>();
using (SqlConnection conn = new SqlConnection(""))
{
    SqlCommand cmd = new SqlCommand("SELECT email FROM dbo.Members", conn);
    conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        items.Add(rdr["email"].ToString());
    }
    rdr.Close();
}

toaddress = string.Join(",", items);

如果您使用的是3.5框架,则需要ToArray()列表。

答案 5 :(得分:0)

var toaddress = new StringBuilder();
var delimiter = "";
using (SqlConnection conn = new SqlConnection(""))
{
    SqlCommand cmd = new SqlCommand("SELECT email FROM dbo.Members", conn);
    conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        toaddress.AppendFormat("{0}{1}", delimiter, rdr["email"].ToString());
        delimiter = ",";
    }
    rdr.Close();
}
return toaddress.ToString();