Change LINQ output. Anonymous type cannot be assigned

Hi, I have a problem, and I’ve cracked it for several hours, I always get an error

Cannot set property or index to 'AnonymousType # 1.XP' - it is read-only

The problem arises on a.XP here

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

and as a comment pointed out that I never say what I want to do, I would like to replace a.XP with an improved score.getLevel (a.XP) value.

Here is the complete code

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();
}
+5
source share
2 answers

Anonymous-typed objects are read only, but given your sample code, it is not enough to try this modification in a loop, just make it part of the query.

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

, , , .

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

// then use it for the query projection

select new CommentData 
{
    // ...
}
+11

# , . , :

  • () XP.
  • , XP:

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

All Articles