简体   繁体   中英

Usage of DefaultIfEmpty combined with FirstOrDefault

I have this code

List<int> input = new List<int>() { 1, 2, 3 };
int output = input.DefaultIfEmpty(-5).FirstOrDefault(x => x == 4);

It says to me "use the value -5 if there is no match"

Why does return this code 0 ?

Your code will return -5 when input is empty.

What you would like to do is

List<int> input = new List<int>() { 1, 2, 3 };
int output = input.Where(x => x == 4).DefaultIfEmpty(-5).FirstOrDefault();

However, you could simplify it as stated in Dmitry Bychenko's answer .

If you want 4 if there's Any 4 in the input and -5 otherwise:

List<int> input = new List<int>() { 1, 2, 3 };
int output = input.Any(x => x == 4) ? 4 : -5;

I think the problem is you're still getting a value. Try this:

int output = input.Where(x => x == 4).DefaultIfEmpty(-5).FirstOrDefault();

Hope it helps!

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