如何在C#中解析以下名称 - 值对的字符串:
string studentDetail = "StudentId=J1123,FirstName=Jack,LastName=Welch,StudentId=k3342,FirstName=Steve,LastName=Smith"
解析此数组的目的是使用Linq to SQL在DB中插入值:
[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();
}
接近这个的最佳方式是什么?
答案 0 :(得分:39)
您可以在逗号上拆分,然后在等号上拆分。我将数据放入字典中以便于访问。
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"];
请注意,这根本不是验证输入,以确保值中没有逗号,没有值没有键,缺少键等等。
答案 1 :(得分:2)
因为个别学生记录在输入中没有分隔,我会做类似以下的事情:
public class Student
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
然后:
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;
}
同样,它有点天真,因为如果内容包含“=”,“,”或“|”,则会出现故障。你也应该在那里添加一些检查。
答案 2 :(得分:1)
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
答案 3 :(得分:0)
Eric Petroelje在https://stackoverflow.com/a/2049079/59996
得到了一个非常好的答案尝试System.Web.HttpUtility.ParseQueryString,传递所有内容 在问号之后。您需要使用System.Web 汇编,但它不应该需要Web上下文。
(我不确定为什么这两个问题没有关联)
我能够使用以下代码解析a = 1&amp; b = 2&amp; c = 3形式的字符串
NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(submission);