2011-12-25 8 views
1

Я получаю следующее сообщение об ошибке:Linq - не может неявно преобразовать тип «System.Collections.Generic.IEnumerable

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'Munchkin.Model.PlayerProfiles.Profile'. An explicit conversion exists (are you missing a cast?) 

Мой код:

Profile currentProfile; 

public Profile ActiveProfile() 
{ 
    currentProfile = new Profile();   
    return currentProfile = 
     (from profiles in xmlDoc.Element("PlayerPofiles").Element("Online").Elements("Player") 
     where (string)profiles.Element("Active") == "True" 
     select new Profile 
     { 
      Name = (string)profiles.Element("Name"), 
      Sex = (string)profiles.Element("Sex"), 
      Avatar = (string)profiles.Element("Avatar").Attribute("path") ?? "", 
      Created = (DateTime)profiles.Element("Created"), 
      Birthday = (string)profiles.Element("Birthday"), 
      Wins = (string)profiles.Element("Ratio").Element("Win"), 
      Losses = (string)profiles.Element("Ratio").Element("Loss"), 
      Abandoned = (string)profiles.Element("Ratio").Element("Abandoned") 
     }); 
} 

ответ

5
public Profile ActiveProfile() 
     { 
      currentProfile = new Profile(); 

      return currentProfile = (from profiles in xmlDoc.Element("PlayerPofiles").Element("Online").Elements("Player") 
          where (string)profiles.Element("Active") == "True" 
          select new Profile 
           { 
            Name = (string)profiles.Element("Name"), 
            Sex = (string)profiles.Element("Sex"), 
            Avatar = (string)profiles.Element("Avatar").Attribute("path") ?? "", 
            Created = (DateTime)profiles.Element("Created"), 
            Birthday = (string)profiles.Element("Birthday"), 
            Wins = (string)profiles.Element("Ratio").Element("Win"), 
            Losses = (string)profiles.Element("Ratio").Element("Loss"), 
            Abandoned = (string)profiles.Element("Ratio").Element("Abandoned") 
           }).FirstOrDefault(); 
     } 

Как ваш currentProfile Одинокий Элемент Profile и запрос назначают коллекцию профиля, поэтому эта ошибка возникает. Попробуйте использовать FirstOrDefault()

+0

Спасибо Dotnetstep ..., что исправил его. – Yecats

+1

вы должны опустить эту строку 'currentProfile = new Profile();', это совершенно не нужно, также метод должен возвращать 'Profile' –

+0

Спасибо @ KrisIvanov - I'v'e удалил первую строку. Я запутался, почему, почему он должен возвращать Profile, а не currentProfile? – Yecats

Смежные вопросы