0

I have a simple class:

public class Item
{
    public int A {get; set;}
    public int B {get; set;}
}

Let's say that I have a collection of Items:

var items = new List<Item>
{
    new Item { A = 1, B = 2},
    new Item { A = 3, B = 4}
};

What I need is a LINQ query to cast each Item object values into string array, so that for example above I will get:

IEnumerable<string []> result = { 
  {"1", "2"}, // First Item
  {"3", "4"} // Second Item
}

Any ideas how to acomplish that?

2 Answers 2

3
items.Select(item => new [] { item.A.ToString(), item.B.ToString() }).ToList()
Sign up to request clarification or add additional context in comments.

1 Comment

The .ToList is redundant, .Select already returns an IEnumerable (as per the OP's requirement). I was about to hit submit on the same answer when you beat me by a second or two.
1

If you're using C#7 you can utilize ValueTuple's instead of an array containing two elements like this:

var result = items.Select(x => (A: x.A.ToString(), B: x.B.ToString()));

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.