如何用逗号字符分隔字符串?

时间:2018-01-12 11:55:09

标签: c# string

我想用逗号分隔两个字符串(即.234,229),我通过添加String.Join()来尝试它。我有下面提到的代码,我在最后一行得到错误。我知道它是一个基本问题,但我是C#编程语言的新手。

 string queryEventID = "";
    foreach (ListItem lstAssign in lstEvent.Items)
    {
       if (lstAssign.Selected == true)
         {                  
            queryEventID = queryEventID + lstAssign.Value + " "; //queryEventID(234 229)                   
            logfield = logfield + "," + lstEvent.SelectedItem.Text;
         }
    }                     
    string queryEventIDs=string.Join(",",queryEventID);//error(cannot convert from string to string[])

3 个答案:

答案 0 :(得分:3)

您应该使用Collection来应用string.Join

来自文档:

  

Join(String, String[]):使用每个元素之间的指定分隔符连接字符串数组的所有元素。

以下是如何在您的情况下使用它的示例。

List<string> queryEventIDList;
foreach (ListItem lstAssign in lstEvent.Items)
{
    if (lstAssign.Selected == true)
    {
        queryEventIDList.Add(lstAssign.Value);                 
        logfield = logfield + "," + lstEvent.SelectedItem.Text;
    }
}
string queryEventIDs = string.Join(",", queryEventIDList);

答案 1 :(得分:1)

您可以使用split函数将字符串转换为集合。

        string queryEventID = "";
        foreach (ListItem lstAssign in lstEvent.Items)
        {
            if (lstAssign.Selected == true)
            {
                queryEventID = queryEventID + lstAssign.Value + " "; //queryEventID(234 229)                   
                logfield = logfield + "," + lstEvent.SelectedItem.Text;
            }
        }

        string queryEventIDs = string.Join(",", queryEventID.Split(' '));

答案 2 :(得分:1)

您可以尝试 Linq 查询该集合:

using System.Linq;

... 

string queryEventID = string.Join(",", lstEvent  // Join query data:  
  .Items                                         //   Having lstEvent.Items
  .OfType<ListItem>()                            //   Obtain IEnumerable<ListItem>
  .Where(item => item.Selected)                  //   Selected only
  .Select(item => item.Value));                  //   Value (not item)

如果你想要一个集合的ids,数组string[]

string[] queryEvents = lstEvent  
  .Items                             
  .OfType<ListItem>()                
  .Where(item => item.Selected)      
  .Select(item => item.Value)
  .ToArray();

string queryEventID = string.Join(",", queryEvents);