Linq - 无法隐式转换类型System.Collections.Generic.IEnumerable

时间:2011-12-25 03:30:56

标签: c# linq error-handling implicit-conversion

我收到以下错误:

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")
        });
}

1 个答案:

答案 0 :(得分: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是Single Profile Item并且查询分配了profile的集合,这就是出现此错误的原因。尝试使用 FirstOrDefault()