Unexpected results in Linq query

I have a Linq query that looks something like this:

var myPosse = from p1 in people
             select p1;
label1.Text = "All my peeps:" + Environment.NewLine;
foreach (Person p in myPosse)
{
    this.label1.Text += p.ToString() + Environment.NewLine;
}

It gives me good results.

But when I do something like this:

var myPosse = from p1 in people
             select p1;
label1.Text = "All my peeps:" + Environment.NewLine;
people.Add(new Person{FirstName="Don", LastName="Cash"});
foreach (Person p in myPosse)
{
    this.label1.Text += p.ToString() + Environment.NewLine;
}

I have an "extra" guy! How does this happen? Var Linq is set up , added an extra guy.

+3
source share
2 answers

This is due to delayed execution, the main feature of Linq.

, var, . . , . .

Linq, . b/c, , , , , . , -, . ( , , , perl PHP).

, , .

var myPosse = from p1 in people
             select p1;
List<Person> theTeam = myPosse.ToList();
label1.Text = "All my peeps:" + Environment.NewLine;
people.Add(new Person{FirstName="Don", LastName="Cash"});
foreach (Person p in theTeam)
{
    this.label1.Text += p.ToString() + Environment.NewLine;
}

ToList(). Linq .ToList(). , "" IEnumerable.

+7

( ) LINQ, , . .

, LINQ IEnumerable<Person>, "people". - ​​ .

"foreach", - , . , .

, LINQ, :

var myPosse = (from p1 in people
         select p1).ToList();  // This makes a copy in a new list...
label1.Text = "All my peeps:" + Environment.NewLine;
people.Add(new Person{FirstName="Don", LastName="Cash"});
foreach (Person p in myPosse)
{
    this.label1.Text += p.ToString() + Environment.NewLine;
    // Don Cash won't show up now, since it wasn't in the original list when the copy was made
}
+3

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


All Articles