简体   繁体   中英

Select query case when with condition with LinQ C#

I would like to add a condition in Select query with r.Field<bool>("isDefault") != false when DetailNo equals to ZZZZZ , I can get all codes as r.Field<string>("Code") with Distinct .

For example:

Code | DetailNo | isDefault                 Code | DetailNo | isDefault
IP6  |   ZZZZZ   | true                      IP6  |   AAAAA   | false
IP7  |   ZZZZZ   | true                      IP7  |   AAAAA   | false
IP7  |   ZZZZZ   | true                           |   AAAAA   | false
IP8  |   ZZZZZ   | false                     IP8  |   AAAAA   | true
IP7  |   ZZZZZ   | true                      IP7  |   AAAAA   | false
IP6  |   ZZZZZ   | true                      IP6  |   AAAAA   | false
IP8  |   ZZZZZ   | false                     IP8  |   AAAAA   | true

Result must be:

Code | DetailNo | isDefault                 Code | DetailNo | isDefault
IP6  |   ZZZZZ   | true                      IP6  |   AAAAA   | false
IP7  |   ZZZZZ   | true                      IP7  |   AAAAA   | false
                                             IP8  |   AAAAA   | true

int countItem = dt
                 .AsEnumerable()
                 .Where(r => r.Field<string>("Code") != "")
                 .Select(r => r.Field<string>("DetailNo") == "ZZZZZ" ? r.Field<string>("Code") : r.Field<string>("Code") + r.Field<int>("TotalID"))
                 .Distinct()
                 .Count();

Change:

Where(r => r.Field<string>("Code") != "")

To this:

Where(r => r.Field<string>("Code") != "" && (r.Field<string>("Code") != "ZZZZ" || r.Field<bool>("isDefault"))))

So, you are filtering by code not empty and (code is equals to ZZZZ or IsDefault is true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM