cmonti
cmonti

Reputation: 187

Override property on IEnumerable object

I have this object:

var child = Mapper.Map<List<ChildViewModel>>( model.ChildData );

and I return this:

return new OutputViewModel
  {
      ChildData = child
  }; 

But In the middle I need to perform a change in one of the child property, I tried this:

var dummy = child.Select(e => e.Number = FormatNumber(e.Number, e.Mask));

so when I return OutputViewModel the job is done, I have my Number property formatted, is there a better way to do it because I don't like it :(

Upvotes: 0

Views: 250

Answers (2)

DLeh
DLeh

Reputation: 24395

Why not make a read-only property that has the number formatted?

public class OutputViewModel
{
    public decimal Number { get; set; }
    public object Mask { get; set; }
    public string NumberFormatted 
    {
        get { return FormatNumber(Number, Mask); }
    }
}

Upvotes: 0

Habib
Habib

Reputation: 223332

LINQ is for querying, not for modifying the collection. You can see the change in your collection because of somewhat side effect due to reference passed to the lambda expression.

A better way would be to use a simple iteration, modify the property of object in each iteration and then return the collection, that will convey the intent in a better way, IMO.

Upvotes: 1

Related Questions