Reputation: 73
In the following code response.Values returns IList>
IList<IList<object>> values = response.Values;
I want to convert values
to List<List<object>>
form. I have already tried using the following statement
List<List<object>> values = response.Values as List<List<object>>
After using this statement
values = null
but
response.Values.Count = 82
How can I resolve this ?
Upvotes: 2
Views: 2062
Reputation: 43936
I don't know why you want to do that, but one way would be this:
var result = values.Select(v => v.ToList()).ToList();
But this could be an expensive operation if the lists are big and I don't see any advantage in converting this. IList<object>
provides the functionality you need.
The only reason I can think of is that you want to pass this to a method that expects List<List<object>>
as parameter type.
ToList()
is a linq extension for an enumeration of type T
that returns a List<T>
containing the elements of the enumeration (T
is object
in your example).
Upvotes: 6
Reputation: 32780
You can do this with reasonable performance the following way:
values.Cast<List<T>>().ToList();
This does does not iterate through all the elements of each List<T>
as René Vogt's answer proposes and the performance gain is quite noticable.
UPDATE. As René Vogt points out, this will fail if the underlying type of the IList
typed objects are not List
s but some other type implementing IList
. In that case you are stuck with using Select
and paying the performance penalty.
If you do know that the underlying type really is a List
then by all means use Cast
as its much faster.
Upvotes: 1
Reputation: 762
I think that you should create a List of List and then in a loop fill it. Something like this:
List<List<object>> list = new List<List<object>>();
foreach(IList<object> l in values){
list.Add(new List<object>(l));
}
I have not test it but I think it should work
Upvotes: 0