2

我有一个元素类型:

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?

4

5 回答 5

10
string[] wantThatArray = infos
    .SelectMany(f => new[] {f.Label, f.Value})
    .ToArray();
于 2012-09-21T13:19:01.820 回答
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;
}
于 2012-09-21T13:17:09.673 回答
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;
}
于 2012-09-21T13:23:36.303 回答
0

另一种变体:

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

嗯,但不是很好.. :( 与其他人相比!

于 2012-09-21T13:29:42.140 回答
-1
FieldInfo[,] infos = new FieldInfo[,]{
                    new FieldInfo{"label1", "value1"},
                    new FieldInfo{"label2", "value2"}
                  };

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

现在您可以简单地转换toinfos.

于 2012-09-21T13:17:55.877 回答