Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

后端 未结 7 1654
忘了有多久
忘了有多久 2020-12-14 06:16

I have a method:

public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname)
{
    DataTransfer.ChargeInSchoo         


        
相关标签:
7条回答
  • 2020-12-14 07:00

    You can use the .ToList() method to convert the IQueryable result returned to an IList, as shown below, after the linq query.

       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).ToList()
                      ;
            result.AddRange(resultV);
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-14 07:02

    SonarQube reported Return an empty collection instead of null. and I had a problem with the error with casting as in the title of this question. I was able to get rid of both only using return XYZ.ToList().AsQueryable(); in a method with IQueryable like so:

    public IQueryable<SomeType> MethodName (...) {
      IQueryable<SomeType> XYZ;
      ...
      return XYZ.ToList().AsQueryable();
    }
    

    Hope so it helps for those in a similar scenario(s).

    0 讨论(0)
  • 2020-12-14 07:03

    If using a where clause be sure to include .First() if you do not want a IQueryable object.

    0 讨论(0)
  • 2020-12-14 07:10

    Try this -->

     new DzieckoAndOpiekun(
                             p.Imie,
                             p.Nazwisko,
                             p.Opiekun.Imie,
                             p.Opiekun.Nazwisko).ToList()
    
    0 讨论(0)
  • 2020-12-14 07:12

    I've got solved my problem this way in EF on list of records from db

    ListOfObjectToBeOrder.OrderBy(x => x.columnName).ToList();
    
    0 讨论(0)
  • 2020-12-14 07:17

    To convert IQuerable or IEnumerable to a list, you can do one of the following:

    IQueryable<object> q = ...;
    List<object> l = q.ToList();
    

    or:

    IQueryable<object> q = ...;
    List<object> l = new List<object>(q);
    
    0 讨论(0)
提交回复
热议问题