开发者

C# anonymous tuple list

开发者 https://www.devze.com 2023-01-05 21:59 出处:网络
Does anyone know of a shorter (hopefully more elegant) way to initialize a collection of anonymous types in C# than the following:

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

精彩评论

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