Roberto Mindoli Roberto Mindoli - 3 months ago 11
C# Question

Add conditional value in Linq from switch case

I have a query that select some value. The code is:

var query = from c in snd.external_invoices.OrderByDescending(x => x.date)
join o in snd.invoices on c.idexternal_invoices equals o.id_external_invoice
select new
{
c.idexternal_invoices,
c.businessname,
o.number,
c.message,
c.price,
c.date,
c.tipologiaPagamento,
c.esitoPagamento,
c.iduser
};


Now i need to select some value in this query based on value in the field c.tipologiaPagamento. In particular, i need to select all the value where c.date it's equal to this switch result:

switch (c.tipologiaPagamento)
{
case "1":
c.date.AddDays(10);
break;
case "2":
c.date.AddDays(10);
break;
case "3":
DateTime endOfMonth = new DateTime(c.date.Year,
c.date.Month,
DateTime.DaysInMonth(c.date.Year,
c.date.Month));
c.date = endOfMonth;
break;
case "4":
DateTime nextMonth = c.date.AddMonths(1);
DateTime endOfNextMonth = new DateTime(c.date.Year,
c.date.Month,
DateTime.DaysInMonth(c.date.Year,
c.date.Month));
c.date = endOfNextMonth;
break;
default:
break;
}


So i need to select in the query the values where c.date is equal to the result of this switch.

How can i do this?

Thanks to all

Answer

I'm not sure you can pass in a complex calculation like ou want easily into a linq expression? Someone can fix me if I'm wrong with this.

What I would do probably, since your calculation depends only on your tipologiaPagamento value only, and uses the date value only in the calculation, which you have in your current result set anyway, not to bother myself doing that on the SQL side. Simply get all the needed information, and put your switch statement into a foreach loop to update the values at the application server level as needed. Probably that'll be able to do the calculation faster than the SQL server, which is not necessarily optimized for data manipulation, but more for data retrieval.

Comments