1

抱歉这个错误,我正在更新问题。我正在编写一个接收以下格式的输入的应用程序:

someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030;

有没有办法可以将这些值添加到泛型LIST<T>中,以便我的列表包含以下内容

record.someid= 00000-000-0000-000000
record.someotherId =123456789
record.someIdentifier =   3030

对不起,我是新手,所以问这个问题。

4

5 回答 5

7
var input = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030;"
var list = input.Split(';').ToList();

添加到文件标题后:

using System.Linq;
于 2013-01-02T16:00:03.323 回答
3

您可以使用Split获取似乎是key / value pair组合的部分字符串并将键和值对添加到Dictionary.

 string str = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030";
 string [] arr = str.Split(';');
 Dictionary<string, string> dic = new Dictionary<string, string>();
 for(int i=0; i < arr.Length; i++)
 {
        string []arrItem = arr[i].Split('=');
        dic.Add(arrItem[0], arrItem[1]);            
 }

根据 OP 的评论进行编辑,以添加到自定义班级列表。

internal class InputMessage
{
     public string RecordID { get; set;}
     public string Data { get; set;}
}

 string str = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030";
    string [] arr = str.Split(';');
List<InputMessage> inputMessages = new List<InputMessage>();
for(int i=0; i < arr.Length; i++)
{
       string []arrItem = arr[i].Split('=');
    inputMessages.Add(new InputMessage{ RecordID = arrItem[0], Data = arrItem[1]});         
}
于 2013-01-02T16:07:54.370 回答
2

如果格式总是那么严格,您可以使用string.Split. 您可以创建一个Lookup

string str = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030;";
var idLookup = str.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries)
    .Select(token => new { 
        keyvalues=token.Split(new[]{'='}, StringSplitOptions.RemoveEmptyEntries)
    })
    .ToLookup(x => x.keyvalues.First(), x => x.keyvalues.Last());

// now you can lookup a key to get it's value similar to a Dictionary but with duplicates allowed
string someotherId = idLookup["someotherId"].First();

演示

于 2013-01-02T16:16:33.913 回答
1

你需要知道在这种情况下Ta 会是什么List<T>,我会把它作为一个字符串。如果您不确定使用object.

List<object> objList = str.Split(new char[] { ';' }).ToList<object>();
于 2013-01-02T16:01:21.103 回答
1

您可以使用以下代码:

        string str = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030;";

        int Start, End = 0;

        List<string> list = new List<string>();

        while (End < (str.Length - 1))
        {
            Start = str.IndexOf('=', End) + 1;
            End = str.IndexOf(';', Start);

            list.Add(str.Substring(Start, End - Start));
        } 
于 2013-01-02T18:44:49.957 回答