解析半冒号将字符串分隔为通用列表<t> </t>

时间:2013-01-02 15:58:29

标签: c# asp.net generics

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

  

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

我是否可以将这些值添加到通用LIST<T>,以便我的列表包含以下内容

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

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

5 个答案:

答案 0 :(得分:7)

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

添加到文件的标题后:

using System.Linq;

答案 1 :(得分: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]});         
}

答案 2 :(得分: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();

Demo

答案 3 :(得分:1)

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

object

答案 4 :(得分: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));
        } 
相关问题