Linq FirstOrDefault - One Liner

I have the following code to determine the age of Person

var pList = ctx.Person.Where(x => x.Create > Date);
int Age = pList.Where(x => x.ID == "foo").FirstOrDefault().Age ?? 20;

I select Personby identifier, if it does not exist, the default value is 20.

The second line is invalid because age cannot be zero, but Person can be. Is there a way to make this work on one line ? I tried with DefaultIfEmpty but it doesn't seem to work.

+4
source share
4 answers

You can use overload Enumerable.DefaultIfEmpty:

int Age = pList
    .Where(x => x.ID == "foo")
    .Select(x => x.Age)
    .DefaultIfEmpty(20)
    .First();

As you can see, it is FirstOrdefaultno longer required, since the default value is accepted if the input sequence is empty (the id filter did not return any faces).

+16
int Age = pList.Where(x => x.ID == "foo").FirstOrDefault()?.Age ?? 20;

# 6.

: enter image description here

+5

:

int Age = pList.Where(x => x.ID == "foo").Select(x=>(int?)x.Age).FirstOrDefault() ?? 20;
+4

It is not beautiful, in any way, but you wanted to do it as short as possible while still counting a few potential NullPointerExceptions. Please do not do this in one liner, and please do not int nullable for this. The code below is not very good and not tested, since I have no opportunity at the moment.

Please note that I would recommend doing it differently, with long if operations, for zero code repetition and readability.

Person person = ctx.Person.Where(x => x.Create > Date && x.ID.Equals("foo")).FirstOrDefault()

int age = (person != null) ? person.Age : 20;
+1
source

Source: https://habr.com/ru/post/1608450/


All Articles