开发者

C# anonymous tuple list

Does anyone know of a shorter (hopefully more elegant) way to initialize a collection of anonymous types in C# than the following:

new[] {
     new[] { "B", "Banana" },
     new[] { "C", "Carrot" },
     new[开发者_如何学Python] { "D", "Durian" },
}.Select(x => new {Value = x[0], Text = x[1] };


You could use a single array, like this:

Warning: Abominable code ahead!

object temp = null;

new object[] {
    "B", "Banana",
    "C", "Carrot",
    "D", "Durian" 
}.Select((v, i) => i % 2 == 0 ? (temp = v) : new { Value = temp, Text = v })
 .Where((v, i) => i % 2 == 1)
 .ToArray() //Important!

Do not do this, EVER!


You nearly had it..

var myCollection = new[]
{
    new { Value = "B", Text = "Banana" },
    new { Value = "C", Text = "Carrot" },
    new { Value = "D", Text = "Durian" }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜