Question

I'm trying to return a result from a list with a Linq method but i get an error saying that I "implictly can't convert my class to generic list. I'm using Get... method.

Would very much appreciate if someone could help me out with this.

This is my Tamagotchi class:

public class Tamagotchi
{
    public string Name { get; set; }
    public DateTime Born { get; set; }
    public int Health { get; set; }
}

This is the API:

public class SomeController : ApiController
{
    List<Tamagotchi> Gotchis = new List<Tamagotchi>
    {
        new Tamagotchi { Born = DateTime.Now.AddYears(-5), Health = 30, Name = "XTP" },
        new Tamagotchi { Born = DateTime.Now.AddYears(-4), Health = 49, Name = "ZQX" },
        new Tamagotchi { Born = DateTime.Now.AddYears(-3), Health = 15, Name = "VBR" },
        new Tamagotchi { Born = DateTime.Now.AddYears(-2), Health = 87, Name = "BNQP" },
        new Tamagotchi { Born = DateTime.Now.AddYears(-1), Health = 62, Name = "VLW" },
    };

    public IEnumerable<Tamagotchi> Get2()
    {
        var _result = Gotchis.SingleOrDefault(tama => tama.Name == "VLW");
        return _result;
    }
}

Thank you!

/Chris

Was it helpful?

Solution

SingleOrDefault will return a single Tamagutchi, so the result is not an IEnumerable at all. Perhaps you mean

public Tamagotchi Get2()
{

    var _result = Gotchis.SingleOrDefault(tama => tama.Name == "VLW");

    return _result;
}

or

public IEnumerable<Tamagotchi> Get2()
{

    var _result = Gotchis.Where(tama => tama.Name == "VLW");

    return _result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top