Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am getting error while converting List to IList. How can I solve this?

What I have tried:

private IList<OrganizationItemDetails> _orgLevel3;
List<OrganizationItemDetails> orgLevel3 = await OrganisationService.GetListOfOrgDetails(3);
 _orgLevel3 = orgLevel3.Select(x => x.EntityCode).ToList();


This line
C#
_orgLevel3 = orgLevel3.Select(x => x.EntityCode).ToList();
I am getting error like cannot implicitly convert type List<string> to IList
Posted
Updated 10-Jul-23 20:15pm
v3

1 solution

The problem isn't the List / IList implicit cast, that works as you would expect:
C#
List<string> myList = new List<string>();
IList<string> myIlist = myList;
The problem is that your IList type doesn't match the List type the Select returns:
C#
private IList<OrganizationItemDetails> _orgLevel3;
Check the type of x.EntityCode and you'll probably find it's a string from yoru question title.

Easy way to check:
C#
var collection = orgLevel3.Select(x => x.EntityCode).ToList();
_orgLevel3 = collection;
If you hover over collection in VS, it'll tell you what type it expands to.
 
Share this answer
 
Comments
Rajesh Kumar 2013 11-Jul-23 2:31am    
'collection' is List<string>. Then how can assign 'collection' value to IList<organizationitemdetails> _orgLevel3's EntityCode ?
OriginalGriff 11-Jul-23 2:49am    
You can't - because there is no conversion from a string to a OrganizationItemDetails. What you need to do is work out how EntityCode relates to OrganizationItemDetails and modify your Select to perform the conversion.
You can't even cast from a collections of a derived class to a collection of it's base class:
        public class baseClass { }
        public class derivedClass : baseClass { }
...
            List<baseClass> listBaseClass = new List<baseClass>();
            List<derivedClass> listDerivedClass = new List<derivedClass>();
            listBaseClass = listDerivedClass;                    // ERROR
            listBaseClass = (List<baseClass>)listDerivedClass;   // ERROR
The only way to do that is to iterate the list and cast the elements to a new collection!
Rajesh Kumar 2013 11-Jul-23 3:21am    
I have written like this _orgLevel3 = orgLevel3.Where(x => x.EntityCode != "").ToList(); Is it okay?
OriginalGriff 11-Jul-23 3:36am    
Should be.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900