Reputation: 1396
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?
Upvotes: 2
Views: 160
Reputation: 2293
another variant:
string[] yourarray = infos.Select(x => string.Format("{0},{1}", x.Label, x.Value))
.Aggregate((x, y) => string.Format("{0},{1}", x, y))
.Split(',');
mhh but not nice.. :( compared to the others !
Upvotes: 0
Reputation: 56688
string[] wantThatArray = infos
.SelectMany(f => new[] {f.Label, f.Value})
.ToArray();
Upvotes: 10
Reputation: 112372
A slightly different variant to Marc Gravell's solution
string[] wantThatArray = new string[infos.Length * 2];
for (int i = 0, k = 0; i < infos.Length; i++, k += 2) {
wantThatArray[k] = infos[i].Label;
wantThatArray[k + 1] = infos[i].Value;
}
Upvotes: 2
Reputation: 17194
FieldInfo[,] infos = new FieldInfo[,]{
new FieldInfo{"label1", "value1"},
new FieldInfo{"label2", "value2"}
};
string[] to = infos.Cast<FieldInfo>().ToArray();
Now you can simply convert to
to infos
.
Upvotes: -1
Reputation: 1062865
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;
}
Upvotes: 8