我想修改传入对象的属性。如何在不创建新实例的情况下执行此操作?
我有课
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; }
}
}
和两种方法
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;
}
请您参考如下方法:
听起来您正在尝试使用 Linq 更新集合中每个对象的属性。 Linq 用于查询,而不是更新。如果您想更新集合中的项目,您必须循环:
foreach(ReportItem item in report.Items)
{
// update item
}
你是否应该这样做是另一个问题,但从机械上讲,你会这样做。
