无法将类型’System.Linq.IQueryable’隐式转换为’System.Collections.Generic.IList’

我有一个方法:

public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname) { DataTransfer.ChargeInSchoolEntities db = new DataTransfer.ChargeInSchoolEntities(); DzieckoAndOpiekunCollection result = new DzieckoAndOpiekunCollection(); if (firstname == null && lastname != null) { IList resultV = from p in db.Dziecko where lastname == p.Nazwisko **select** new DzieckoAndOpiekun( p.Imie, p.Nazwisko, p.Opiekun.Imie, p.Opiekun.Nazwisko) ; result.AddRange(resultV); } return result; } 

和选定位置的错误:

错误1无法将类型’System.Linq.IQueryable ‘隐式转换为’System.Collections.Generic.IList ‘。 存在显式转换(您是否错过了演员?)

知道如何解决我的问题吗?

要将IQuerableIEnumerable转换为列表,您可以执行以下操作之一:

 IQueryable q = ...; List l = q.ToList(); 

要么:

 IQueryable q = ...; List l = new List(q); 

您可以用var resultV替换IList resultV var resultV

如果使用where子句,请确保包含.First()如果您不需要IQueryable对象。

试试这个 – >

  new DzieckoAndOpiekun( p.Imie, p.Nazwisko, p.Opiekun.Imie, p.Opiekun.Nazwisko).ToList() 

您可以使用.ToList()方法将返回的ILueryable结果转换为IList,如下所示,在linq查询之后。

  public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname) { DataTransfer.ChargeInSchoolEntities db = new DataTransfer.ChargeInSchoolEntities(); DzieckoAndOpiekunCollection result = new DzieckoAndOpiekunCollection(); if (firstname == null && lastname != null) { IList resultV = from p in db.Dziecko where lastname == p.Nazwisko **select** new DzieckoAndOpiekun( p.Imie, p.Nazwisko, p.Opiekun.Imie, p.Opiekun.Nazwisko).ToList() ; result.AddRange(resultV); } return result; } 

我已经通过这种方式解决了我在db上的记录列表中的问题

 ListOfObjectToBeOrder.OrderBy(x => x.columnName).ToList();