如何从由逗号和换行符分隔的源字符串填充List <t> </t>

时间:2014-01-05 14:28:36

标签: c# list

我有一个字符串

string strsource = "0,0,200,0,206,2,28515663\r\n0,0,200,0,206,2,2029\r\n0,0,200,1,8,2,2039\r\n0,0,200,1,12,2,2039\r\n0,0,200,2,8,2,2039\r\n0,0,200,2,12,2,2039\r\n0,0,200,3,8,2,2040\r\n0,0,200,3,12,2,2040\r\n";

以及具有属性

的类
public class justme
{
    public string field1 {get; set; }
    public string field2 {get; set; }
    public string field3 {get; set; }
    public string field4 {get; set; }
    public string field5 {get; set; }
    public string field6 {get; set; }
    public string field7 {get; set; }
}

填充List<justme>的最佳方法是,\r\n

知道源上的字段由逗号和列表中的新项分隔

2 个答案:

答案 0 :(得分:0)

拆分,循环,拆分,分配:

List<justme> justmes = new List<justme>();
foreach(var line in Regex.Split(strsource, "\r\n")) {
  string[] fields = line.Split(',');

  justmes.Add(new justme {
    field1 = fields[0];
    field2 = fields[1];
    // field3 = ...
    // etc...
  });
}

答案 1 :(得分:0)

这是一个很好的方式。

var lines = strsource.Split(new string[] { "\r\n" }, StringSplitOptions.None)
.Where(line => line != string.Empty)
.Select(line =>
{
    var cols = line.Split(',');

    var me = new justme();
    {
        me.field1 = cols[0];
        me.field2 = cols[1];
        me.field3 = cols[2];
        me.field4 = cols[3];
        me.field5 = cols[4];
        me.field6 = cols[5];
        me.field7 = cols[6];
    }

    return me;
}).ToArray();
相关问题