How many times is IENumerable ordered?

I know that when I repeat IEnumerable, I repeat the original set, so if I changed the original set in the next IEnumerable iteration, it counted the modification.

So I wonder how this affects this when I have ordered IEnumerable.

For example, if I have this:

List<MyType> myNoOrderedList //add my items

IEnumerable<MyType> myOrderedIEnumerable = myNoOrderedList
  .OrderBy(x => x.Property);

foreach(MyType in myOrderedIEnumerable)
{
    //Do something
}

Suppose I have 3 elements in a list, at each iteration in an IEnumerable list is ordered or is only one list ordered once?

What happens if I add or remove an item in Do something? Does IEnumerable have initial ordered items or must order again to have a list change account?

+4
source share
3

:

  • ( , )
  • myOrderedIEnumerable, myNoOrderedList :

:

 List<string> initial = new List<String>() {
   "a", "z", "e", "d";
 };

 // Nothing will be done at this point (no ordering)
 var ordered = initial.
   .OrderBy(x => x.Property);

 // ordered has not materialized here, so it'll feel Addition
 initial.Add("y"); // <- will be added into ordered 

 // Here on the first loop ordered will be materialized and since
 // initial and ordered are different collection now, we can modify 
 // initial without changing ordered
 foreach (var item in ordered) {
   if (item == "a") {
     initial.Add("b");
     initial.Remove("z");
   } 

   Console.WriteLine(item);
 }

:

a
d
e
y <- before materialization
z 

. , , materization - : :

  • , . .ToList(), .Any(), .FirstOrDefault()
  • , . .OrderBy ( )
  • , . .Where(), .SkipWhile() - .

Linq .

+5

, 3 , IEnumerable ?

, .
, .
foreach try..finally , .

, " -" ? IEnumerable , ?

myNoOrderedList, IOrderedEnumerable, .
, , - , .

, (miOrderedIEnumerable ), InvalidOperationException, : " ; ".

+2

, OrderBy, . :

int[] array = { 2, 1, 3 };
var ordered = array.OrderBy(x => x);

foreach (int i in ordered)
{
    array[1] = 0;
    Debug.Write(i);             // 123
}

foreach (int i in ordered)
    Debug.Write(i);             // 023
0

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


All Articles