Is there any way to set a property in the middle of a query?
var products = from p in Products
let pricecalc = p.IsDiscontinued ? 0 : p.UnitPrice
// somehow set p.Price = pricecalc
select p;
I know i could use select new Product { .. set props here .. } but i dont want to do this.
At the moment, i am thinking i am going to have to use a foreach to do this.
Instead of
let pricecalc = p.IsDiscontinued ? 0 : p.UnitPrice
Use
let pricecalc = (p.Price = p.IsDiscontinued ? 0 : p.UnitPrice)
Yes, but you need an extension method:
public static TSource Apply<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
where TSource : class // wouldn't work for value types, since the action would work on a copy
{
foreach(var item in source)
{
action(item);
yield return item;
}
}
You can then use it like this:
var products = Products.Apply(p => p.Price = p.IsDiscontinued ? 0 : p.UnitPrice);
However I wouldn't recommend doing this; Linq queries are not supposed to produce side effects. You should probably change your query to return new objects that contain the updated price.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With