0

I have the following code

var result = data.Select(a => new { Id = a.Id, text = a.Type, assetName  = a.Value}).Take(10).OrderBy(a => a.text).ToList();

I want to concatenate Type and Value in a single value and assign this value to the text like that

foreacah(var item in result)
{
  item.text = item.text + " | " + item.assetName;
}

Is there a way to achieve this?

Alex T
  • 75
  • 5
  • 3
    Does this answer your question? [How to set value for property of an anonymous object?](https://stackoverflow.com/questions/17441420/how-to-set-value-for-property-of-an-anonymous-object) – ColinM Dec 10 '20 at 12:12
  • You will have to use reflection, or not use anonymous types. Anonymous types are *supposed* to be immutable, though using reflection you can circumvent this. From regular C#, however, you can't. – Lasse V. Karlsen Dec 10 '20 at 12:13
  • Why not just do the concatenate in your ```.Select(a =>``` – MichaelMao Dec 10 '20 at 12:37

1 Answers1

1

Anonymous objects are usually used within a create-once and read-once-context. Performing any logic on them doesn´t fit to that concept.

However as you´re iterating that collection anyway, you can also just create another one where you create new objects - that again are readonly.

var result = data.Select(a => new { Id = a.Id, text = a.Type, assetName  = a.Value}).Take(10).OrderBy(a => a.text).ToList();
var modified = result.Select(x => new { 
    Id = x.Id,
    text = x.text + "|"  x.assetName },
    assetName = x.AssetName 
});
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111