问题
Is it possible to declare an object that is is a list of lists of a generic types.
So a little like private List<List<T>> outerList = new List<List<T>>();
but a statement that actually compiles.
I do not want to use dynamics like so: private List<List<dynamic>> list2 = new List<List<dynamic>>();
as I would like type safety.
I'd kind of like to be able to:
foreach(List<T> innerList in outerList)
{
foreach(T item in innerList)
{
doSomethingTo(item);
}
}
Ideally I'd like to declare a class that inherits from the List<List<T>>
EDIT:
I probably should have been clearer. The inner lists must be able to have different types. so one inner list may be List<string>
and another List<int>
FURTHER EDIT:
Following @ErikE's request the question has been reworded here.
回答1:
Sure, you can define that as a generic class:
public class Foo<T> : List<List<T>>
{
}
and then have a generic method that processes one of them:
public void Process<T>(Foo<T> outerList)
{
foreach(List<T> innerList in outerList)
{
foreach(T item in innerList)
{
doSomethingTo(item);
}
}
}
of course doSomethingTo
would then need to be generic as well.
I probably should have been clearer. The inner lists must be able to have different types. so one inner list may be
List<string>
and anotherList<int>
Yes, you should have been clearer. There's no inheritance relationship between List<string>
and List<int>
that would allow you to store them in a single type-safe outer collection. You would have to resort to List<object>
or List<dynamic>
, or find a different data structure that meets your needs.
回答2:
You can't have a List<List<T>>
that its T
could be variable in each item. For example if T=string
then your list is List<List<string>>
and you can not have any List<int>
in your top list.
The list you can use is List<List<object>>
and the thing that will help you to be typed when working with list, is Cast<T>
method like this:
var list = new List<List<object>>();
var intList = new List<int>() { 1, 2, 3 };
var stringList = new List<string>() { "a", "b", "c" };
list.Add(intList.Cast<object>().ToList());
list.Add(stringList.Cast<object>().ToList());
var sum = 0;
list[0].Cast<int>().ToList()
.ForEach(i =>
{
sum += i;
});
var msg = "";
list[1].Cast<string>().ToList()
.ForEach(s =>
{
msg += s;
});
Benefits:
- We add items typed: (
List<int>
,List<string>
) - We use items typed: (
Cast<int>
,Cast<string>
)
回答3:
If we recall the times of .NET 1.1, there is also a bunch of classes in System.Collections namespace that almost nobody uses nowadays. With that said you could come with something like this:
System.Collections.Generic.List<System.Collections.ArrayList> outerList =
new System.Collections.Generic.List<System.Collections.ArrayList>();
来源:https://stackoverflow.com/questions/32770783/how-to-declare-an-object-that-is-a-list-of-lists-of-a-generic-type