Home > database >  How to join two arrays in C# using a single line of code
How to join two arrays in C# using a single line of code

Time:11-17

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#?

CodePudding user response:

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:

  • The names.Zip(values, <something>) part produces a sequence of values based on applying the "something" to each pair of values from names and values.
  • The (n, v) => $"{n}:{v}" part takes a name and a value, and formats them as name:value.
  • The 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.

  • Related