Dig*_*ers 4 c# linq anonymous-types
有没有办法在构建过程中访问匿名类型的成员?
例如
enumerable.select(i => new
{
a = CalculateValue(i.something), // <--Expensive Call
b = a + 5 // <-- This doesn't work but i wish it did
}
Run Code Online (Sandbox Code Playgroud)
愿意考虑替代方案以实现相同的目标,这基本上是我预测我的枚举和投影的一部分是一个昂贵的计算,其价值被多次使用,我不想重复它,也重复那个打电话只是感觉不干.
这是不可能的,因为尚未实际分配新的匿名对象,因此其属性也不可用.您可以执行以下操作:
enumerable.select(i =>
{
//use a temporary variable to store the calculated value
var temp = CalculateValue(i.something);
//use it to create the target object
return new
{
a = temp,
b = temp + 5
};
});
Run Code Online (Sandbox Code Playgroud)