C#lambda表达式中的类型转换错误

问题描述:

我创建了一个ILIst<Person>的对象。该列表包含Person类型的对象。 现在我想使用基于特定条件的lambda表达式过滤此列表。所以,我做了如下:C#lambda表达式中的类型转换错误

IList<Person> personlist = new IList<Person>; 
... 
... 
... 

IList<Person> filtered_person = 
     (IList<Person>)personlist.Where(pd => pd.name != "anil"); 

,但此行给出了错误为:

Unable to cast object of type 'WhereListIterator`1[Person]' to type 'Person'. 

什么可以错在这里?

无需铸造。如果需要,可以使用ToList()扩展方法创建列表:

IList<Person> filteredPerson = personlist.Where(pd => pd.name != "anil").ToList(); 

使用

IList<Person> filtered_person = (IList<Person>)personlist.Where(pd => pd.name != "anil").ToList(); 

你表达式的结果是IEnumerable<Person>和需要转换到一个列表。