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

net*_*jor 29 .net c# linq linq-to-entities exception-handling

我有一个方法:

public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname)
{
    DataTransfer.ChargeInSchoolEntities db = new DataTransfer.ChargeInSchoolEntities();
    DzieckoAndOpiekunCollection result = new DzieckoAndOpiekunCollection();
    if (firstname == null && lastname != null)
    {
        IList<DzieckoAndOpiekun> 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;
}
Run Code Online (Sandbox Code Playgroud)

和选定位置的错误:

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

任何想法如何解决我的问题?

Ars*_*nko 48

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

IQueryable<object> q = ...;
List<object> l = q.ToList();
Run Code Online (Sandbox Code Playgroud)

要么:

IQueryable<object> q = ...;
List<object> l = new List<object>(q);
Run Code Online (Sandbox Code Playgroud)


小智 10

您可以替换IList<DzieckoAndOpiekun> resultV使用var resultV.

  • 这是一个比其他人更好的答案.特别是如果`AddRange()`接受一个`IEnumerable <T>`(它几乎肯定会......) (3认同)

kra*_*s88 6

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