Reputation: 683
I have c# code:
string[] names = new [] { "a", "b", "c" };
int[] vals = new[] { 5, 10, 15 };
r = "";
for( int i = 0; i < names.Length; i++ )
r += names[i] + ": " + vals[i] + " ";
In python I can write oneliner
r = " ".join( [ names[i] + ":" + str(vals[i]) for i in range(len(names)) ] )
How can i do this in c#?
Upvotes: 0
Views: 395
Reputation: 1500495
I would take a slightly different approach to the Python code - I'd use the LINQ "zip" operator to produce a sequence of strings you want to join together, then use string.Join
to join them:
string result = string.Join(" ", names.Zip(values, (n, v) => $"{n}:{v}");
So within that:
names.Zip(values, <something>)
part produces a sequence of values based on applying the "something" to each pair of values from names
and values
.(n, v) => $"{n}:{v}"
part takes a name and a value, and formats them as name:value.string.Join(" ", <sequence>)
part joins the sequence elements together with a space between each pair of values.Note that this doesn't end up with a trailing space, unlike the original C# code.
Upvotes: 6