Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

c# - 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

question from:https://stackoverflow.com/questions/15749445/is-there-a-trick-in-creating-a-generic-list-of-anonymous-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...