Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify LINQ output AnonymousType cannot be assigned

Tags:

c#

.net

linq

Hi i have a problem and ive been hacking at it for hours i keep getting the error

Property or indexer 'AnonymousType#1.XP' cannot be assigned to -- it is read only

The problem occurs on the a.XP here

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

and as a comment pointed out i never say what i want done, i whould like to substitute a.XP with the improved value score.getLevel(a.XP).

Here is the full 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();
}
like image 726
Thomas Andreè Wang Avatar asked Mar 18 '12 02:03

Thomas Andreè Wang


2 Answers

Anonymously-typed objects are read only, but given your code sample, there is little need to try this modification in the loop, simply make it part of your query execution.

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

If you find yourself in need of performing changes after the query has executed, then you should go ahead and define a class that allows such mutations and then select into that class instead of the anonymous type.

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

// then use it for the query projection

select new CommentData 
{
    // ...
}
like image 136
Anthony Pegram Avatar answered Oct 26 '22 04:10

Anthony Pegram


Anonymous types in C# are immutable and there is nothing you can do about it. As I see it, you have two options:

  1. Create a normal (named) type that has a mutable property XP.
  2. Copy the contents of the old object into new one, except XP:

    var modifiedComments = comments.Select(
        c => new
        {
            c.UserName,
            c.PostTitle,
            c.UserImage,
            c.Comment,
            c.UserID,
            XP = score.getLevel(c.XP)
        });
    
like image 44
svick Avatar answered Oct 26 '22 04:10

svick