parse a string with name-value pairs

How can I parse the following string of name-value pair in C#:

string studentDetail = "StudentId=J1123,FirstName=Jack,LastName=Welch,StudentId=k3342,FirstName=Steve,LastName=Smith"

The purpose of parsing this array is to insert values in DB using Linq to SQL:

    [HttpPost()]
    public ActionResult SaveStudent(string studentDetail)
    {
        DataContext db = new DataContext();         

                Student student = new Student();
                {
                    student.StudentID = //StudentID
                    student.FirstName = //FirstName
                    student.LastName = //LastName

                };

                db.Student.InsertOnSubmit(student);
                db.SubmitChanges();

            return View();
    }

What is the best way of approaching this?

Answers


You can split on the comma, then on the equals sign. I put the data into a dictionary for easy access.

string input = "StudentId=J1123,FirstName=Jack,LastName=Welch,StudentId=k3342,FirstName=Steve,LastName=Smith";

Dictionary<string,string> keyValuePairs = input.Split(',')
  .Select(value => value.Split('='))
  .ToDictionary(pair => pair[0], pair => pair[1]);

string studentId = keyValuePairs["StudentId"];

Note that this isn't validating the input at all to ensure that there are no commas in values, no keys without values, missing keys, etc.


Because the individual student records are not delimited in the input, I would do something like the following:

public class Student
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
} 

and then:

private List<Student> DoSplit(string input)
{
var theReturn = new List<Student>();
input = input.Replace(",StudentId=", "|,StudentId=");

var students = input.Split('|');

foreach (var student in students)
{
    var attribs = student.Split(',');
    if (attribs.Count() == 3)
    {
        var s = new Student();
        s.Id = attribs[0].Substring(attribs[0].LastIndexOf('='));
        s.FirstName = attribs[1].Substring(attribs[1].LastIndexOf('='));
        s.LastName = attribs[2].Substring(attribs[2].LastIndexOf('='));

        theReturn.Add(s);
    }
}

return theReturn;
}

Again, it's a bit naive because if content contains "=", ",", or "|", there will be failures. You should add some checking in there as well.


string sourceStr= "StudentId=J1123,FirstName=Jack,LastName=Welch,StudentId=k3342,FirstName=Steve,LastName=Smith";

Dictionary<string,string> names=new Dictionary<string,string>();
string[] arr = sourceStr.Split(',');         
foreach (var ar1 in arr)
{
    string[] itemArr= ar1.Split('=');
    if (itemArr.Length > 1)
    {
        names.Add(itemArr[0], itemArr[1]);
    }
}
//check names now

Eric Petroelje had a very nice answer at https://stackoverflow.com/a/2049079/59996

Try System.Web.HttpUtility.ParseQueryString, passing in everything after the question mark. You would need to use the System.Web assembly, but it shouldn't require a web context.

(I'm not sure why these two questions aren't linked)

I was able to parse a string of the form a=1&b=2&c=3 using the following code

NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(submission);

Need Your Help

C - determine if a number is prime

c# c primes

I am trying to come up with a method that takes an integer and returns a boolean to say if the number is prime or not and I don't know much C; would anyone care to give me some pointers?

Mongoose Trying to open unclosed connection

node.js mongodb mongoose

This is a simplified version of the problem, but basically I'm trying to open 2 mongodb connections with mongoose and it's giving me "Trying to open unclosed connection." error.