Home > Software design >  C# - Cant convert var to List
C# - Cant convert var to List

Time:11-16

This code snippet returns me an error,

public List<auto> autoSelect()
{
       return autoSelect(DateTime.Today);
}
public List<auto> autoSelect(DateTime date)
{
       var onderhoudAuto = (from onderhoud in db.onderhouds 
                            where onderhoud.uitvoerdatum != DateTime.Today 
                            select onderhoud)
                          .FirstOrDefault();
       List<string> autos = (from auto in db.autos 
                             where auto.autoId.Equals(onderhoudAuto) 
                             select auto)
                            .FirstOrDefault();
       return autos;
}

I tried convert the var to a list with .ToList(); although this doesn't work. Does anyone have any suggestions?

CodePudding user response:

I tried convert the var to a list

No, you do not. VAR is not actually a data type - it is resolved by the compiler. A tooltip should show you the real type.

Your problem is another one:

List autos = return autos;

This is a list of STRINGS. The return of List, though, and auto is not string. Period.

public List autoSelect(DateTime date)

The method return type is wrong. Thus it does not match. NTOHING has anything to do there with VAR - it is simply you selecting as single property and returning a list of strings, but that is not what the method is programmed to return.

CodePudding user response:

If you use FirstOrDefault() after your linq query, you are saying you want the first element (or the default -usually null- for the datatype if none matches) in the LINQ query, not a list of elements.

If you want a list of elements, use ToList() on the linq query, not try to convert a single entity to a list.

If you, for some reason, want a list of a single entity, then create a list (with new List<type>()) and then add your entity (of the same type as your list) to the list.

  • Related