Linq Choose why I get the result?

I get a very strange result with my linq query, which I don't understand:

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

Suppose I have ICollection<Person>one entry and this person has an addressnull

When I do the following linq statement:

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

a variable testis a list with 1 entry, which null.

  • Why exactly do I get one entry nullinstead of an empty list?
  • What do I need to change to get an empty list?

Thanks in advance

+4
source share
3 answers

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

Because Select is a projectionit will only give the result of the address, so null

From MSDN

Projects each element of a sequence into a new form.

What do I need 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;
+4

where, , , null:

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

, , .

+3

LINQ is just a bunch of specialized iterations.

At the end of the day, your extension method call Selectlooks something like this:

foreach(Person person in persons)
{
    // This is equivalent to person => person.Address
    yield return person.Address;
}

... and therefore you get a set of strings where there is one nullítem.

On the other hand, if you want to filter the sequence so that you don't get a collection with nulllinks, what would you do without LINQ? Maybe something like this:

foreach(Person person in persons)
{
    if(person.Address != null)
        yield return person.Address;
}

... And in the LINQ world Where, then Select:

persons.Where(person => person.Address != null).Select(person => person.Address);
+1
source

All Articles