Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert List<List<object>> to IList<IList<object>>

Tags:

c#

.net

list

I have written a method which is public List<List<object>> Fetch(string data), inside I create List<List<object>> p = new List<List<object>>();

my boss now wants to return a IList<IList<object>> instead of List<List<object>> ie
public IList<IList<object>> Fetch(string data),

so when I try do return (IList<IList<object>>) p; //throws an exception

How do I convert List<List<object>> to IList<IList<object>> and back to List<List<object>>

like image 784
david Avatar asked Jan 25 '12 16:01

david


People also ask

How to convert List into IList in c#?

IList<IList<object>> p = new List<List<object>>(); Then this would be valid: List<List<object>> listOfLists = new List<List<object>>(); IList<IList<object>> p = listOfLists; p. Add(new object[]); List<object> list = p[0];

What is the difference between List and IList in C#?

The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.

What is IList type in C#?

In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.


2 Answers

You can't perform that conversion via straight casting - it wouldn't be safe. Instead, you should use:

IList<IList<object>> ret = new List<IList<object>>(); 

Then for each "sublist" you can use:

// Or whatever ret.Add(new List<object>()); 

Finally, just return ret.

You could use LINQ to perform the conversion of your existing List<List<object>> when you return it - but it would be better to just create a more appropriate type to start with, as shown above.


To understand why some of the existing answers are wrong, suppose you could do this:

IList<IList<object>> p = new List<List<object>>(); 

Then this would be valid:

List<List<object>> listOfLists = new List<List<object>>(); IList<IList<object>> p = listOfLists; p.Add(new object[]); List<object> list = p[0]; 

But p[0] is a reference to an object[], not a List<object>... our supposedly type-safe code doesn't look as safe any more...

Fortunately, IList<T> is invariant to prevent exactly this problem.

like image 138
Jon Skeet Avatar answered Sep 18 '22 01:09

Jon Skeet


You would have to declare your list as

IList<IList<object>> list = new List<IList<object>>(); // Works! 

This works, because only the outer list is created in the first place. You can then insert individual items that are compatible with IList<object>:

list.Add(new List<object>()); list.Add(new object[10]); 
like image 23
Olivier Jacot-Descombes Avatar answered Sep 19 '22 01:09

Olivier Jacot-Descombes