有誰知道的短(希望更優雅)的方式在C#初始化匿名類型的集合比下面C#匿名元組列表
new[] {
new[] { "B", "Banana" },
new[] { "C", "Carrot" },
new[] { "D", "Durian" },
}.Select(x => new {Value = x[0], Text = x[1] };
有誰知道的短(希望更優雅)的方式在C#初始化匿名類型的集合比下面C#匿名元組列表
new[] {
new[] { "B", "Banana" },
new[] { "C", "Carrot" },
new[] { "D", "Durian" },
}.Select(x => new {Value = x[0], Text = x[1] };
你可以使用一個單一的陣列,像這樣:
警告:可惡的代碼提前!
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!
你近了吧..
var myCollection = new[]
{
new { Value = "B", Text = "Banana" },
new { Value = "C", Text = "Carrot" },
new { Value = "D", Text = "Durian" }
};
這是嚴重錯誤的代碼! :) – 2010-07-05 02:16:06
哈哈好吧,是的,這是擺脫了重複,你可以隱藏Linq調用自定義擴展方法...但代碼仍然可怕,就像你說的。 – cbp 2010-07-05 02:17:36