adam78 adam78 - 7 months ago 27
C# Question

C# Filtering a list using Linq requires ToList method to be called?

I'm trying to filter a list using Linq in c# as follows?

// Returns a List<Person>
var personList = getPersons();

if (!string.IsNullOrEmpty(PersonName.Text))
personList = personList.Where(x => x.Name.Contains("Joe"));

But I get error:

Cannot convert source type 'System.collections.Generic.Ienumerable<Mysite.Models.Person>' to target type 'System.collection.Generic.List<Mysite.Models.Person>

I have to do the following to fix i.e add ToList()

personList = personList.Where(x => x.Name.Contains("Joe")).ToList();

My question is why do I need to call ToList when the personList is already a list of type


Where returns an IEnumerable<T> and the getPersons() method returns a List<Person>. You can substitute a List<T> for an IEnumerable<T> but not the other way round.

As to how to fix it, it depends. If you want to use a method from List<T> on the collection of Person, then calling .ToList() is the correct way to handle it for example .ForEach().

On the other hand if you don't need any methods / properties from List<T> then you can either declare the variable as IEnumerable<Person> personList = getPersons(); or change the return type of getPersons().

From MSDN:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, 
IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>