【问题标题】:Retrieving and using values from a comma seperated string [duplicate]从逗号分隔的字符串中检索和使用值[重复]
【发布时间】:2014-07-01 08:49:56
【问题描述】:

我在每个单词之间有一个用逗号分隔的字符串,即 car,tent,pan,torch

我想在每个逗号处拆分字符串,并能够获取每个单独的字符串并将其插入到我的数据库中。

• 所以在每个逗号处分割字符串,

• 遍历每个值并将其插入我的数据库

【问题讨论】:

  • 您能解释一下为什么将 values 数组中的每个字符串都设置为该数组第二个条目中的值吗? (值[1])。
  • 你为什么不把这个逻辑直接转移到数据库中......
  • 请改写问题,因为不清楚您要问什么。
  • 嗨,我刚刚在网上找到了这段代码,如果你知道更好的方法,请告诉我:)
  • 我想你只是在输入“i”的地方输入了“1”,除此之外它看起来还不错。但您可能仍想考虑 Krishnraj Rana 所说的话。听起来很有用。

标签: c# asp.net string tags


【解决方案1】:
var input = "car,tent,pan,torch";
foreach (var s in input.Split(',')) {
  insertintodb(s);
}

【讨论】:

  • 我可以投票赞成。这足以解决这个问题:)
【解决方案2】:

你可以试试这个:

// Split the comma separated list to an array that will contain the words you want.
string[] words = commaSeparatedList.Split(',');

// Iterate through the words in array called words
foreach(string word in words)
{
    // Code for insert the word in your database. 
}

但是,我必须在此指出,上述方法并不是最优的。我之所以这么说,是因为对于words 中的每个单词,您都必须往返数据库才能将其插入数据库的相应表中。话虽如此,我建议您创建一个存储过程,您将在其中传递此字符串,然后在您的数据库中尝试从逗号分隔列表中获取单词并将它们插入相应的表中。后者只是到数据库的一次往返。

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多