Process list by adding it to c #?

Is there some kind of list, such as a collection, that I can use in .NET to allow me to join it during iteration?

var ls = new List<int>();
ls.Add(5);

foreach (var v in ls) {
    if (v > 0)
        ls.Add(v - 1);
}

//Alternative
var e = ls.GetEnumerator();
while (e.MoveNext()) {
    if (e.Current > 0)
        ls.Add(e.Current - 1);
}
+4
source share
6 answers

To simulate such a loop foreach, I suggest using a loop for, iterating backwards:

for (int i = ls.Count - 1; i >= 0; --i) {
  var v = ls[i];

  //TODO: put relevant code from existing foreach loop here  
} 

Or if you need to go ahead

int n = ls.Count; // we don't want iterate the items appended

for (int i = 0; i < n; ++i) {
  var v = ls[i];

  //TODO: put relevant code from existing foreach loop here  
}

If you want to assign added elements (see comments below), a standard loop is enough for:

for (int i = 0; i < ls.count; ++i) {
  var v = ls[i];

  //TODO: put relevant code from existing foreach loop here  
} 

Finally, you can iterate a copy of the source list:

foreach (var v in ls.ToList()) { // ls.ToList() is a shallow copy of the ls
  ...
}  
+6
source

Use forwould allow this. foreachdoes not allow modification of the enumerated upon repeating it.

var ls = new List<int>();
ls.Add(5);

for (int i = 0; i < ls.Count; i++) {
  var v = ls[i];
  if (v > 0)
      ls.Add(v - 1);
}

foreach (var v in ls) {
    Console.WriteLine(v.ToString());
}

Conclusion:

5
4
3
2
1
0
+2

, . :

var ls = new List<int>();
ls.Add(5);

var tempList = new List<int>();
foreach(var v in ls){
   if(v>0)
        tempList.Add(v-1);
}

//Update list
foreach(var v in tempList){
   ls.Add(v);
}

//Dont forget to clear the tempList if you need it again !
+1

, :

for (int i = 0; i < ls.Count; i++)
{
    if (ls[i] > 0) ls.Add(ls[i] - 1);
}

( foreach), :

foreach (int i in ls.ToList())
{
    if (i > 0) ls.Add(i - 1);
}
+1

; , , ; - :

public List<int> AddByReduceNo(List<int> list, int no)
{
    if (no > 0)
    {
        list.Add(no - 1);
        return AddByReduceNo(list, no - 1);
    }

    return list;
}

ls.Add(5) ls = AddByReduceNo(ls, 5);,
ls = AddByReduceNo(ls, 6);

+1

BlockingCollection , .

GetConsumingEnumerable, IEnumerable, , , . .

This is especially useful if you have a consumer and a thread manufacturer.

0
source

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


All Articles