Gordnfreeman
Gordnfreeman

Reputation: 1615

Using Split and storing in a data table

I am looking at how to split a string and store the info in a datatable. I can get the split and store to work correctly but the issue comes in how I am trying to use the split. this is an example of the string I have:

 itemid/n3,itemid/n4

itemid is the items unique id and after /n is how many of the item the user has selected, the comma seperates the entries

I have a data table like this:

DataTable table = new DataTable();
table.Columns.Add("id", typeof(int));
table.Columns.Add("count", typeof(int));

Id like to be able to split the string at the comma and then store each of the values in the data table so they appear on the same row (split at the /n) is there an easy way to do this using split? or am I better off doing it another way

Upvotes: 0

Views: 3034

Answers (3)

Harps
Harps

Reputation: 672

Note that for the example, I changed the type of the first column, as in the provided sample string, id is a string.

        DataTable table = new DataTable();
        table.Columns.Add("id", typeof(string));
        table.Columns.Add("count", typeof(int));

        var str = "itemid/n3,itemid/n4";
        var items =
            str.Split(',').Select(
                r =>
                new
                    {
                        Id = r.Split(new[] {"/n"}, StringSplitOptions.RemoveEmptyEntries).First(),
                        Count = int.Parse(r.Split(new[] {"/n"}, StringSplitOptions.RemoveEmptyEntries).Last())
                    });

        foreach (var item in items)
        {
            var row = table.NewRow();
            row["id"] = item.Id;
            row["count"] = item.Count;
        }

Upvotes: 1

Dracorat
Dracorat

Reputation: 1194

If "/n" and "," are always present for each record, you can use a regular expression split with the expression "(?:/n|\,)" and then loop with x+=2 instead of x++ through the list. X will be the ID, X+1 will be the value.

string Input = "12/nTwelve,13/nThirteen,";
string[] InputSplit = Regex.Split(Input, @"(?:/n|\,)");
for(int i = 0 ; i < ((InputSplit.Length / 2) * 2) ; i+=2){ 
    //Math in the middle helps when there's a trailing comma in the data set
    Console.WriteLine(string.Format("{0}\t{1}", InputSplit[i], InputSplit[i+1]));
}

Upvotes: 2

Matthias Meid
Matthias Meid

Reputation: 12513

Yeah, you may split by the comma first and by /n afterwards:

foreach(var row in myString.Split(','))
{
    var fields = row.Split(new string[] { "/n" },
        StringSplitOptions.None);
    // fields[0] is ID, fields[1] is count
}

This still executes in linear time, therefore it may definitely be a way to go.

Upvotes: 3

Related Questions