如何将数组转换为双倍如此大的数组?

时间:2012-09-21 13:13:20

标签: c#

我有一个元素类型:

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

我有一个充满FieldInfo个对象的数组。

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

现在我想将该数组转换为包含以下值的新数组:

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

是否有一种简短的方法可以将infos等数组转换为wantThatArray之类的数组? 也许使用LINQ的Select?

5 个答案:

答案 0 :(得分:10)

string[] wantThatArray = infos
    .SelectMany(f => new[] {f.Label, f.Value})
    .ToArray();

答案 1 :(得分:8)

我会保持简单:

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;
}

答案 2 :(得分:2)

与Marc Gravell的解决方案略有不同的变体

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;
}

答案 3 :(得分:0)

另一种变体:

string[] yourarray = infos.Select(x => string.Format("{0},{1}", x.Label, x.Value))
                          .Aggregate((x, y) => string.Format("{0},{1}", x, y))
                          .Split(',');

mhh但不好...... :(与其他人相比!

答案 4 :(得分:-1)

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

string[] to = infos.Cast<FieldInfo>().ToArray();

现在,您只需将to转换为infos