-4

I have a string with commas between each word to seperate them i.e. car,tent,pan,torch

I want to split the string at each comma and be able to take each separate string and insert it into my database.

• So split the string at each comma,

• loop through each value inserting it into my database

Paul Kirkason
  • 227
  • 2
  • 4
  • 20
  • 3
    Can you explain why you set every string in the values array to the value in the second entry of that array? (values[1]). – Steve Jul 01 '14 at 08:52
  • 1
    Why don't you shift this logic directly into databse.... – Krishnraj Rana Jul 01 '14 at 08:52
  • 1
    Please rephrase the question, because it's unclear what you're asking for. – Tarec Jul 01 '14 at 08:52
  • Hi, i just found this piece of code online, if you know a better way to do it please let me know :) – Paul Kirkason Jul 01 '14 at 08:56
  • I think you just typed "1" where you ment "i", apart from that it looks OK. But you stil might want to consider what Krishnraj Rana says. That sounds useful. – Michiel Jul 01 '14 at 08:56
  • I think you should delete your own post. You've no idea what do you want to ask for and I'd recommend you to start from some basic C# tutorial before asking ridiciolously broad questions. – Tarec Jul 01 '14 at 09:07

2 Answers2

2
var input = "car,tent,pan,torch";
foreach (var s in input.Split(',')) {
  insertintodb(s);
}
derpirscher
  • 14,418
  • 3
  • 18
  • 35
1

You could try this one:

// 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. 
}

However, I have to point out here that the above approach is not optimal. The reason why I say this is the fact that for each word you have in the words you would have to make a round trip to the database to insert it into the corresponding table of your database. That being said I would suggest you create a stored procedure, in which you will pass this string, and then in your database you would try to get the words from the comma separated list and insert them in the corresponding table. The latter would be only one round trip to the database.

Christos
  • 53,228
  • 8
  • 76
  • 108