【问题标题】:LINQ query to return collection of original object with a transformed propertyLINQ 查询以返回具有转换属性的原始对象的集合
【发布时间】:2018-11-28 16:25:00
【问题描述】:

我目前有工作代码

foreach (var item in list)
{
    item.Property1= SomeFunction(item.Property1);
}

return list;

我想将其转换为 LINQ 查询,但我不太确定如何去做。我怀疑我需要使用 .Select 但我不确定如何正确执行此操作。我的尝试是:

return list.Select(r => SomeFunction(r.Property1));

当然,它只返回一个属性集合,而我想要一个原始对象的集合,其中包含一个改变的属性。

【问题讨论】:

  • list.ForEach(x => x.Property1 = SomeFunction(item.Property1);??
  • Lina 表达式旨在无副作用。我认为你应该坚持使用foreach

标签: c# linq


【解决方案1】:

总的来说,我认为这可能是个坏主意,但你去吧......

你想要像list.Select(x => { SomeFunction(x); return x; }); 这样的东西,其中SomeFunction 是一个转换你想要的属性的函数。

完整示例:

public class A { public int Data { get; set; } }

public void SomeFunction(A a)
{
    a.Data *= 2;
}

var listy = new List<A>() { 
    new A() { Data = 3 }, 
    new A() { Data = 5 } 
};

listy.Select(x => { SomeFunction(x); return x; })

输出(C# 交互式外壳):

Enumerable.WhereSelectListIterator<Submission#9.A, Submission#9.A> { Submission#9.A { Data=6 }, Submission#9.A { Data=10 } }

【讨论】:

  • 正确。这是个坏主意。无法保证枚举将永远运行,因此对象可能保持不变。
【解决方案2】:

假设list 的类型为List&lt;&gt;

list.ForEach(x =&gt; x.Property1 = SomeFunction(item.Property1));

但是foreach 到底有什么问题呢?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多