Can you enumerate a collection in C# out of order?

前端 未结 11 2111
天涯浪人
天涯浪人 2020-12-17 17:15

Is there a way to use a foreach loop to iterate through a collection backwards or in a completely random order?

11条回答
  •  情深已故
    2020-12-17 18:06

    Do you want to rand a collection and interect with it?

    If yes, try this:

    Random rand = new Random(Environment.TickCount);
    
    test.Sort((string v1, string v2) => {
                    if (v1.Equals(v2))
                    {
                        return 0;
                    }
    
                    int x = rand.Next();
                    int y = rand.Next();
    
                    if (x == y)
                    {
                        return 0;
                    }
                    else if (x > y)
                    {
                        return 1;
                    }
    
                    return -1; 
                });
    
    for (string item in test)
    {
      Console.WriteLn(item);
    }
    // Note that test is List;
    

提交回复
热议问题