Anatoly
Anatoly

Reputation: 1916

How to modify properties of the incoming object without creating a new instance?

I would like to modify properties of the incoming object. How to do this without creating a new instance?

I have a class

public class Report : IReport<ReportItem>
{
    public Report()
    {
        Items = new ReportItemsCollection();
    }

    public Report(IEnumerable<ReportItem> items)
    {
        Items = new ReportItemsCollection(items);
    }

    [DataMember(Name = "items")]
    public ReportItemsCollection Items { get; private set; }

    IEnumerable<ReportItem> IReport<ReportItem>.Items
    {
        get { return Items; }
    }
}

and two methods

private static Report ConvertReportItems(Report report)
{
    var reportData = report.Items.Select(BackwardCompatibilityConverter.FromOld);
    return new Report(reportData);
}

public static ReportItem FromOld(ReportItem reportItem)
{
    reportItem.AgentIds = new List<Guid> { reportItem.AgentId };
    reportItem.AgentNames = new List<string> { reportItem.Agent };

    return reportItem;
}

Upvotes: 1

Views: 349

Answers (2)

D Stanley
D Stanley

Reputation: 152626

It sounds like you're trying to update the properties of each object in a collection with Linq. Linq is for querying, not updating. If you want to update the items in a collection, you'll have to loop:

foreach(ReportItem item in report.Items)
{
   // update item
}

Whether you should do this or not is another question, but mechanically that's how you would do it.

Upvotes: 3

StriplingWarrior
StriplingWarrior

Reputation: 156634

Make sure Report allows you to set its properties. I'm going to suppose you've got a Data property or something like that, which has a setter.

private static void ConvertReportItems(Report report)
{
    report.Data = report.Items.Select(BackwardCompatibilityConverter.FromOld)
        .ToList();
}

Upvotes: 1

Related Questions