Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you set a property in a linq query before selecting the item?

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.

like image 505
4imble Avatar asked Dec 21 '25 23:12

4imble


2 Answers

Instead of

 let pricecalc = p.IsDiscontinued ? 0 : p.UnitPrice

Use

 let pricecalc = (p.Price = p.IsDiscontinued ? 0 : p.UnitPrice)
like image 65
Tilak Avatar answered Dec 24 '25 12:12

Tilak


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.

like image 35
Thomas Levesque Avatar answered Dec 24 '25 13:12

Thomas Levesque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!