How could I improve this C# randomising method?

前端 未结 7 2176
南方客
南方客 2021-02-10 20:30

I think I\'ve settled on this as the most simple and unit-testable method for randomising a list, but would be interested to hear of any improvements.

public sta         


        
7条回答
  •  既然无缘
    2021-02-10 20:43

    Not sure how much of an improvement this is, but would have performance benefits if the list is large and you only need the first few random items.

    public static IEnumerable RandomiseList(IList list, int seed)
    {
        Random random = new Random(seed);
        List takeFrom = new List(list);
    
        while (takeFrom.Count > 0)
        {
            int pos = random.Next(0, takeFrom.Count - 1);
            T item = takeFrom[pos];
            takeFrom.RemoveAt(pos);
            yield return item;
        }
    }
    

    Removes the need for a temp list or even a temp swap variable.

    If I was going to be using this a lot, I'd rewrite it as an extension method.

提交回复
热议问题