2

I have a list of string:

var list = new List<string>();

Data in the list is in this format A1_A2_A3, A1_A2_A3, A1_A2_A3

I want to split each element A1_A2_A3 of list by _ and store the result into List<Item>

Where Item is a class containing three properties a1, a2, a3

I want to do it using LINQ, I can do this by using loop but I'm looking for solution using LINQ Only

Here is my working:

list.Select(x => x.Split('_').Select(s => new Item()
                {
                    a1 = x[0],
                    a2 = x[1],
                    a3 = x[2]
                }))
5
  • you'll probably need to tell split which character to use, x.Split("_") for the underscore. Commented Jan 25, 2018 at 13:59
  • Yes, I forget to add x.Split("_"). I've updated my question Commented Jan 25, 2018 at 14:06
  • What do you mean with "linq only"? I can see only linq-code in your question. Commented Jan 25, 2018 at 14:07
  • 1
    @HimBromBeere They should have said "Here is my non-working attempt:" Commented Jan 25, 2018 at 14:08
  • @HimBromBeere, for the linq only, I meant that I'm looking for solution in linq although it solution can also be achieved using loop. Commented Jan 27, 2018 at 18:41

2 Answers 2

3

What you want to do is take each part of the split and put in a different property:

var result = list.Select(x => {
    var parts = x.Split('_');
    return new Item { a1 = parts[0], a2 = parts[1], a3 = parts[2] };
}).ToList();

Note that this does not check for value index passed to indexer. If you want to verify then you could:

var result = list.Select(x => {
        var parts = x.Split('_');
        return parts.Length == 3 ? new Item { a1 = parts[0], a2 = parts[1], a3 = parts[2] : null };
    }).Where(i => i != null).ToList();
Sign up to request clarification or add additional context in comments.

Comments

3

You need to split on '_' and your selects are off, you first need to select the Split result and then you index into the result array, your code indexes into the original string (x)

var list = new List<string>();
list
    .Select(x => x.Split('_'))
    .Select(s => new Item()
    {
        a1 = s[0],
        a2 = s[1],
        a3 = s[2]
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.