C #, a collection that contains different types of lists

I currently have a class that contains 3 dictionaries, each of which contains lists of the same type in each dictionary, but different types in dictionaries, such as:

Dictionary1<string, List<int>> ... Dictionary2<string, List<double>>... Dictionary3<string, List<DateTime>>...

Is there a way to use another collection that can contain all lists so that I can iterate through the list collection? The possibility of iteration is the only requirement for such collection, sorting, and other operations are not required.

I want to have access to the list directly through a string or another identifier and access members of the list. The type of security is not a requirement, but in return I don’t want to throw something, the speed here is absolutely important.

So, when the calculations are performed on the members of the list, knowledge of the exact type is assumed, for example, "double lastValue = MasterCollection [" List1 "] Last ();", while it is assumed that List1 is a list of type double.

Can this be done? Sorry that I sometimes use the wrong or incomplete terminology. I am not a trained programmer or developer.

Thanks Matt

+4
source share
2 answers

To do this, you will need to use a non-generic API, for example IList (not IList<T> ) - i.e. Dictionary<string, IList> . Or, since you just need to iterate, maybe just IEnumerable (not IEnumerable<T> ). But! This will mean that you are not speaking general, so some sacrifices may be necessary (boxing of value types during extraction, etc.).

With an IList / IEnumerable score to customize your example:

 double lastValue = MasterCollection["List1"].Cast<double>().Last(); 

You could, of course, write a few custom extension methods on IDictionary<string,IList> , which would do something more:

 double lastValue = MasterCollection.Get<double>("List1").Last(); 

I'm not sure if it’s worth it.

+3
source

No, what you are trying to do is impossible; namely, the requirement for strong printing on all lists without casting is what prevents the rest.

If your only requirement is to iterate over each of the elements in the list, then you can create your dictionary as Dictionary<string, IEnumerable> (note the non-common interface). IEnumerable<T> comes from IEnumerable , which will allow you to repeat each item in a list.

The problem is that you will need to throw at some point either in IEnumerable<T> (if you know you are working with it) or use Cast<T> in the Enumerable class (the latter is worse, as you may suffer boxing / unpacking, unless it throws a type, in which case you would not have a performance penalty).

I would say that you should not store items in the same list; your usage example shows that you know the type ahead of time (you assign a double) so that you know at that point in time a specific typed list.

Do not lose type safety.

0
source

All Articles