与解析名称 - 值对的字符串 [英] parse a string with name-value pairs

查看:115
本文介绍了与解析名称 - 值对的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何解析名称 - 值对下列字符串在C#中:

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"



解析此阵的目的是使用LINQ to SQL的数据库中插入值:

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?

推荐答案

您可以拆分的逗号,然后在等号。我把数据放到一个字典,方便访问。

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.

这篇关于与解析名称 - 值对的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆