Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Select why am I getting a result?

Tags:

c#

.net

linq

I am getting a very strange result with my linq query that I don't understand:

public class Person 
{
    public Address Address { get; set; }
    public string Name { get; set; }
    ...
}

Imagine that I have a ICollection<Person> with one entry and that person is having a Address null

When I do the following linq statement:

var test = person.Select(x => x.Address).ToList();

the test variable is a List with 1 entry which is null.

  • Why exactly do I get one null entry instead of an empty list?
  • What would I have to change to get an empty list?

Thanks in advance

like image 373
xeraphim Avatar asked Feb 10 '23 23:02

xeraphim


2 Answers

Why exactly do I get one null entry instead of an empty list?

Because Select is a projection and it will give just the result of adress so null

From MSDN

Projects each element of a sequence into a new form.

What would I have to change to get an empty list?

 var test = person.Where(x => x.Address != null).Select(x => x.Address).ToList();

or in LINQ Query Expression

var t = from p in person
                where p.Adresse != null
                select p.Adresse;
like image 73
BRAHIM Kamel Avatar answered Feb 12 '23 15:02

BRAHIM Kamel


Add a where statement to limit the results so that it contains only persons for which address is not null:

var test = person.Where(x => x.Address != null).Select(x => x.Address).ToList();

If you don't do this, your results are not filtered and you just get back a projection of all elements in the collection.

like image 32
L-Four Avatar answered Feb 12 '23 13:02

L-Four