【问题标题】:Modify LINQ output AnonymousType cannot be assigned修改 LINQ 输出 AnonymousType 无法分配
【发布时间】:2012-03-18 10:10:23
【问题描述】:

嗨,我有一个问题,我已经破解了好几个小时我一直收到错误

无法将属性或索引器“AnonymousType#1.XP”分配给 -- 它 是只读的

问题出现在a.XP这里

    foreach (var a in comments)
    {
        a.XP = score.getLevel(a.XP);
    }

正如评论指出的那样,我从不说我想要做什么,我想用改进的值 score.getLevel(a.XP) 替换 a.XP。

这是完整的代码

protected void GetComments()
{
    TimberManiacsDataContext db = new TimberManiacsDataContext();
    Score score = new Score();
    var comments = (from fComment in db.Comments
                    where fComment.PublishID == Convert.ToInt32(Request.QueryString["Article"])
                    orderby fComment.DateTime descending
                    select new
                    {
                        UserName = fComment.User.UserLogin.Username,
                        PostTime = fComment.DateTime,
                        UserImage = fComment.User.UserGeneralInfo.ProfilePicture,
                        Comment = fComment.Comment1,
                        UserID = fComment.UserID,
                        XP = fComment.User.CommunityScore
                    }).Take(10).ToList();

    foreach (var a in comments)
    {
        a.XP = score.getLevel(a.XP);
    }
    Commentlist.DataSource = comments;
    Commentlist.DataBind();
}

【问题讨论】:

  • 错误信息的哪一部分你不明白?
  • 如何解决,我想用新的和改进的值 score.getLevel(a.XP) 替换 a.XP
  • 顺便说一句,在 C# 中将方法命名为 GetScore 而不是 getScore 是惯例。类的公共表面区域应该使用这个版本的 PascalCasing。 camelCasing 是为私人成员、本地人等保留的。
  • 嗯,谢谢你的提醒,顺便说一句受保护的方向是什么?
  • 由于 protected 对派生类可见,出于设计目的,您应该简单地将其视为公共 API 的一部分。但我应该澄清一下,属性和方法应该是 PascalCased,公共与否。

标签: c# .net linq


【解决方案1】:

匿名类型的对象是只读的,但鉴于您的代码示例,几乎不需要在循环中尝试此修改,只需将其作为查询执行的一部分即可。

XP = score.getLevel(fComment.User.CommunityScore)

如果您在查询执行后发现自己需要执行更改,那么您应该继续定义一个允许此类突变的类,然后选择该类而不是匿名类型。

class CommentData { ... } // define this type with your properties

// then use it for the query projection

select new CommentData 
{
    // ...
}

【讨论】:

  • 那行得通,我认为右侧已转换为 SQL,我尝试按照我认为应该是输出 score.getLevel(XP) = a.User.CommunityScore 的方式进行操作,但没有工作我只是拒绝尝试对方,事实上有点尴尬。
【解决方案2】:

C# 中的匿名类型是不可变的,您对此无能为力。在我看来,您有两种选择:

  1. 创建具有可变属性XP 的普通(命名)类型。
  2. 将旧对象的内容复制到新对象中,XP 除外:

    var modifiedComments = comments.Select(
        c => new
        {
            c.UserName,
            c.PostTitle,
            c.UserImage,
            c.Comment,
            c.UserID,
            XP = score.getLevel(c.XP)
        });
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多