Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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<Tuple<Tank,Tank>> mylist = new List<Tuple<Tank,Tank>>(); 

and then when i iterate over the list i access them by

mylist[i].item1 ... mylist[i].item2 ... 

It's very confusing and i always forget what is item1 and what is item2, if i could access them by :

mylist[i].AttackingTank... mylist[i].TargetTank... 

It would be much clearer, is there a way to do it without defining a class:

MyTuple { public Tank AttackingTank; public Tank TargetTank; } 

I want to avoid defining this class because then i would have to define many different classes in different scenarios, can i do some "trick" and make this anonymous.

Something like :

var k = new {Name = "me", phone = 123}; mylist.Add(k); 

The problem of course that i don't have a type to pass to the List when i define it

like image 918
OopsUser Avatar asked Apr 01 '13 18:04

OopsUser


People also ask

What can anonymous types be created?

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

When can anonymous types be created?

We can create anonymous types by using “new” keyword together with the object initializer. As you can see from the below code sample, the type is store in a var and has two data items.

Do anonymous types work with Linq?

You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.


2 Answers

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); 
like image 144
alex Avatar answered Sep 19 '22 19:09

alex


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); 
like image 40
moribvndvs Avatar answered Sep 19 '22 19:09

moribvndvs