2013-12-19 71 views
0

我試圖從Linq方法返回列表的結果,但我得到一個錯誤,說我「不能將我的類轉換爲通用列表我使用得到...方法錯誤試圖通過Linq和Mvc Web API傳遞IEnumerable列表

將非常感激,如果有人可以幫助我這個

這是我的寵物蛋類:。

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

這是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; 
    } 
} 

謝謝!

/克里斯

回答

0

的SingleOrDefault會返回一個Tamagutchi,所以結果不能作爲IEnumerable的。也許你的意思是

public Tamagotchi Get2() 
{ 

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

    return _result; 
} 

public IEnumerable<Tamagotchi> Get2() 
{ 

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

    return _result; 
} 
+0

噢ofcourse,謝謝! SingleOrDefault和IEnumerable dos'nt聽起來很不錯= P thx又一次! – koffe14