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
269 views
in Technique[技术] by (71.8m points)

c# - Dictionary of generic lists or varying types

I want to have a Dictionary that maps strings to generic lists of varying types. i.e. in the following form:

Key        Value
string     List<T>
string     List<U>
string     List<V>
string     List<U>
...

Currently I'm using a Dictionary<string, IList> and then extracted the strongly typed list from each dictionary KeyValuePair<string, IList> pair entry as follows:

Type layerType = pair.Value.GetType().GetGenericArguments()[0];
List<layerType> objectsClicked = pair.Value as List<layerType>;

Is there a nicer way to do this?

[Edit] As has been noted, the above doesn't compile, apologies - that's what you get when you ask a question while you're still working on somethings. Some more explanation. I'm making a basic spatial data viewer. The final view consists of a group of Layer<T>s. Each layer provides a delegate to render its type (given an offset and scale) and a way to check which of its objects are in the current window. For hit testing, I would like a List for each Layer of which objects have been hit. That list would be a List<Point> for a Point layer, etc... The grouping of the hits from all the Layer<T>s would then be a collection of strongly typed lists.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

How about Dictionary<string, dynamic> assuming you're on C# 4

Dictionary<string, dynamic> Dict = new Dictionary<string, dynamic>();
Dict.Add("int", new List<int>());
Dict.Add("string", new List<string>());

Dict["int"].Add(12);
Dict["string"].Add("str");

foreach (KeyValuePair<string, dynamic> pair in Dict) {
   Type T = pair.Value.GetType();
   Console.WriteLine(T.GetGenericArguments()[0].ToString());
}

That prints out

System.Int32

System.String

Is that what you're looking for?


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

...