RealWorldCoder
RealWorldCoder

Reputation: 1021

How to turn IEnumerable to string array of combined values

Lets say I had my object:

public class MyObject{ public p1; public p2; }

And the enumerable version:

IEnumerable<MyObject> MyObjects;

How would I turn it into a string[] that would be an array of p1 + '=' + p2 values?

Upvotes: 0

Views: 64

Answers (2)

Rune FS
Rune FS

Reputation: 21752

You could do some simple linq on it

(from m in MyObjects
select m.p1 + "=" + p2).ToArray()

if you don't really need it as an array you can omit the call to ToArray() and you'd then have an IEnumerable<string> instead

If you wish to put them all into a comma separated list you don't need to transform to an array since the string.Joinmethod has an over load that takes an enumerable. So you can do this:

string.Join(",",from m in MyObjects
                select m.p1 + "=" + p2);

I personally prefer the above syntax but if you are all for using fewer letters then the code is semantically equal to the below shorter snippet

string.Join(",",MyObjects.Select(m => m.p1 + "=" + p2));

Upvotes: 2

user4133849
user4133849

Reputation:

MyObjects.Select(o => o.p1 + "=" + o1.p2).ToArray()

Upvotes: 0

Related Questions