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
.
null
entry instead of an empty list?Thanks in advance
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With