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

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

最佳答案

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 是单个配置文件项并且查询分配配置文件集合,这就是出现此错误的原因。尝试使用 FirstOrDefault()

关于c# - Linq - 无法隐式转换类型'System.Collections.Generic.IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8628064/

相关文章:

c# - 优雅的解决方案 - 使用 Linq-To-SQL 批量删除和重新添加相关的子列表

ruby-on-rails-3 - 如何摆脱 Rails 3 中 decl_auth 中 "You are not allowed to access this action."的空白错误页面?

c# - 选择列表中特定元素位于列表首位的列表子集

c# - 在 Xamarin studio(Android 应用程序)中序列化/反序列化列表<>

c# - 使用 LINQ 获取 IEnumerable<T> 中的第一个(也是唯一一个)元素有什么好处吗?

用于 SQL 插入的 PHP Try and Catch

php - 日志中有很多Cakephp警告

c# - 使用 linq 和 lambda 表达式简化传统的 foreach 嵌套循环

c# - 在同一屏幕位置创建新表单

sql - 如何使用 LINQ 生成 SQL?