【问题标题】:Separate string by comma into a class [duplicate]用逗号将字符串分隔成一个类[重复]
【发布时间】:2018-09-25 12:40:03
【问题描述】:

我正在使用一个包含多个值的字符串: 示例

string Response="John,13,1st,Mike,15,3st"...and so on

这 3 个值需要在单独的类对象中插入每个值。 示例

class Students
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string  SchoolClass{ get; set; }
}

我需要以我的列表为例

 Students mItems = new List<Students>();
 mItems.Add(new Students() { Name = first string value,Age=second,SchoolClass=third....and so on

或者如果使用我的字符串和键值方法更简单

姓名:John,年龄:13,学校班级:1st .....等等

【问题讨论】:

  • 如果值顺序是确定的,则使用拆分方法并从数组中为属性分配值。
  • 那么,您的问题是什么?您遇到了什么问题?您现在刚刚描述了一个任务
  • 是的,订单是特定的。我会怎么做?是不是用键值法比较好?
  • 听起来你需要一个 CSV 解析器
  • public string Age { get; set; } type int 在这里会更有意义

标签: c#


【解决方案1】:

String.Split 和一个 for 循环:

List<Students> studentList = new  List<Students>();
string[] tokens = Response.Split(',');
for(int i  = 0; i <= tokens.Length - 3; i+=3)
{
    Students s = new Students {Name = tokens[i], Age = tokens[i + 1], SchoolClass = tokens[i + 2]};
    studentList.Add(s);
} 

【讨论】:

  • 谢谢你的好例子!
  • @iBug:我注意到并标记为垃圾邮件。顺便说一句,为什么仍然没有办法 PM/通知某人?
  • @iBug:那么,如果您想与某人交谈,则无需对随机帖子发表评论。尤其是因为这与问题或答案无关,对其他人来说并不有趣。
  • @TimSchmelter 之后我可以删除这些 cmets。我只是想提醒其他人采取了不当行为。
  • @iBug:当然,这种解决方法“有效”,但我不明白为什么 SO 不允许直接与用户交流(如果你生气了,你可以阻止某人)。
猜你喜欢
  • 2021-10-09
  • 2014-08-22
  • 2016-03-13
  • 2012-12-22
  • 1970-01-01
  • 2023-04-09
  • 2020-12-04
  • 1970-01-01
  • 2018-07-29
相关资源
最近更新 更多