Losbear
Losbear

Reputation: 3315

Convert custom delimited string to List<myClass>?

How do I turn this:

string x = "key:value|key:value|key:value|key:value";

into this?

List<myClass> listObj;

myClass definition:

public class myClass
{
    public string keyName { get; set; }
    public string keyValue { get; set; }
}

There has to be a way to do it using LINQ or something :) thanks in advance!

* NOTE * I should add I know how to do this splitting it and looping through it, but there has to be a better way :)

Upvotes: 1

Views: 1656

Answers (3)

Ehsan
Ehsan

Reputation: 32701

Do this if you prefer to use your custom class instead of Dictionary

 var result = from y in x.Split('|')
             let obj = y.Split(':')
             select new myClass{keyName = obj[0], keyValue = obj[1]};

 var list = result.ToList();   

Upvotes: 0

Tim
Tim

Reputation: 15237

Well, since you really wanted to avoid splitting and looping...

public List<MyClass> Parse(string base, string workingName, string workingValue,
                           bool processingName = true, 
                           List<MyClass> workingList = null, int index = 0)
{
    if (workingList == null)
        workingList = new List<MyClass>();

    if (index >= base.Length)
    {
        return workingList;
    }
    if (base[index] = '|')
    {
        workingList.Add(new MyClass { keyName = workingName, keyValue = workingValue });
        return Parse(base, "", "", true, workingList, index + 1);
    }
    else if (base[index] = ':')
    {
        return Parse(base, workingName, "", false, workingList, index + 1);
    }
    else if (processingName)
    {
        return Parse(base, workingName + base[index], "", processingName, workingList, index + 1);
    }
    else
    {
        return Parse(base, workingName, workingValue + base[index], processingName, workingList, index + 1);
    }
}

But please, for the love of whatever you hold dear, don't do anything even remotely resembling that (and yes, this is untested, hand-written code, so there are probably errors - just making a joke about avoiding things).

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

This will require separate ToList() call, but I like query syntax for its declarative nature:

from s in x.Split('|')
let parts = s.Split(':')
select new myClass { 
    keyName = parts[0], 
    keyValue = parts[1] 
}

Or you can use fluent syntax:

x.Split('|')
 .Select(s => {
    var parts = s.Split(':');
    return new myClass { 
        keyName = parts[0], 
        keyValue = parts[1] 
    };
 }).ToList()

Upvotes: 10

Related Questions