Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array to a double so big array?

Tags:

c#

I have an element type:

public class FieldInfo
{
  public string Label { get; set; }
  public string Value { get; set; }
}

And I have an array filled with FieldInfo objects.

FieldInfo[] infos = new FieldInfo[]
                      {
                        new FieldInfo{Label = "label1", Value = "value1"},
                        new FieldInfo{Label = "label2", Value = "value2"}
                      };

Now I want to convert that array to a new one that contains following values:

string[] wantThatArray = new string[] {"label1", "value1", "label2", "value2"};

Is there a short way to do the conversion from an array like infos to an array like wantThatArray?
Maybe with LINQ's Select?

like image 486
thersch Avatar asked Nov 29 '25 06:11

thersch


2 Answers

string[] wantThatArray = infos
    .SelectMany(f => new[] {f.Label, f.Value})
    .ToArray();
like image 144
Andrei Avatar answered Nov 30 '25 18:11

Andrei


I would keep it simple:

string[] wantThatArray = new string[infos.Length * 2];
for(int i = 0 ; i < infos.Length ; i++) {
   wantThatArray[i*2] = infos[i].Label;
   wantThatArray[i*2 + 1] = infos[i].Value;
}
like image 34
Marc Gravell Avatar answered Nov 30 '25 19:11

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!