Home > Backend Development > C++ > How to Implement a SQL CASE Statement in LINQ using C#?

How to Implement a SQL CASE Statement in LINQ using C#?

Susan Sarandon
Release: 2024-12-27 22:42:10
Original
200 people have browsed it

How to Implement a SQL CASE Statement in LINQ using C#?

LINQ CASE Statement Implementation for Complex Conditions

A CASE statement is a powerful tool for evaluating multiple conditions and returning specific results based on each case. This article aims to provide a clear explanation and solution to implementing CASE statements in LINQ for C#.

In one specific scenario, a query seeks to update stock status based on a set of conditions:

osc_products.products_quantity =
      CASE 
         WHEN itempromoflag <> 'N' THEN 100000
         WHEN itemcat1 IN ('1','2','31') AND itemsalestatus = 'S' THEN 100000
         WHEN itemsalestatus = 'O' THEN 0
         ELSE cds_oeinvitem.itemqtyonhand - cds_oeinvitem.itemqtycommitted 
      END 
Copy after login

To translate this CASE statement to LINQ, we can employ the following syntax:

query.Select(item => item.Products_Quantity = 
  item.ItemPromoFlag != 'N' ? 100000 : 
  (item.ItemCat1 == "1" || item.ItemCat1 == "2" || item.ItemCat1 == "31") && item.ItemSaleStatus == "S" ? 100000 : 
  item.ItemSaleStatus == "O" ? 0 : 
  cds_oeinvitem.ItemQtyOnHand - cds_oeinvitem.ItemQtyCommitted);
Copy after login

This LINQ expression uses ternary operators to emulate the CASE statement's conditions and set the corresponding values to the Products_Quantity property. The result is a query that updates the stock status based on the specified conditions.

Note that the provided code snippet assumes that you have already established a LINQ query using an appropriate data source. The query variable in the code should represent the LINQ query you have created.

The above is the detailed content of How to Implement a SQL CASE Statement in LINQ using C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template