pitersmx
pitersmx

Reputation: 957

c# get objects properties values into string array

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?

Upvotes: 0

Views: 633

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56469

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()));

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101711

items.Select(item => new [] { item.A.ToString(), item.B.ToString() }).ToList()

Upvotes: 3

Related Questions