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" }
};
精彩评论