Is there a trick in creating a generic list of anonymous type?

前端 未结 9 1700
有刺的猬
有刺的猬 2021-01-30 05:25

Sometimes i need to use a Tuple, for example i have list of tanks and their target tanks (they chase after them or something like that ) :

List

        
相关标签:
9条回答
  • 2021-01-30 06:01

    You can create an empty list for anonymous types and then use it, enjoying full intellisense and compile-time checks:

    var list = Enumerable.Empty<object>()
                 .Select(r => new {A = 0, B = 0}) // prototype of anonymous type
                 .ToList();
    
    list.Add(new { A = 4, B = 5 }); // adding actual values
    
    Console.Write(list[0].A);
    
    0 讨论(0)
  • 2021-01-30 06:03

    Or even more simple

            var tupleList = (
               new[] {
                    new { fruit = "Tomato", colour = "red"},
                    new { fruit = "Tomato", colour = "yellow"},
                    new { fruit = "Apple", colour = "red"},
                    new { fruit = "Apple", colour = "green"},
                    new { fruit = "Medlar", colour = "russet"}
                }).ToList();
    

    Which loses the static function.

    0 讨论(0)
  • 2021-01-30 06:08

    You could use a List<dynamic>.

     var myList = new List<dynamic>();
     myList.Add(new {Tank = new Tank(), AttackingTank = new Tank()});
    
     Console.WriteLine("AttackingTank: {0}", myList[0].AttackingTank);
    
    0 讨论(0)
提交回复
热议问题