Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to use a Predicate to extract certain data into a list C#

I have an instance that contains a List that contains a set of records. I have created another instance of this list where I only want to pull out the active records, but this is the error it throws:

Message=Unable to cast object of type ‘WhereListIterator1[Namespace.Class]' to type 'System.Collections.Generic.List1[Namespace.Class]’.

Here is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public async Task CompareList(List<ListClass> listInstance1)
{
    List<ListClass> listInstance2 = new List<ListClass>();
    listInstance2 = (List<ListClass>)listInstance1.Where(x => x.Active == "A");
}

>Solution :

the problem in your code is that you try to cast IEnumerable<T> to List<T>

you have two options, either use .ToList() as suggested in the other answer, or pass the filtered list as a parameter to construct a new list as shown in the following code:

public async Task CompareList(List<ListClass> listInstance1)
{
 List<ListClass> listInstance2 = new(listInstance1.Where(x => x.Active == "A"));
}  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading