ASP.net列表随机排序

时间:2011-06-09 14:43:07

标签: asp.net asp.net-mvc random

如何获取列表并随机订购?

List< Testimonial > testimonials = new List< Testimonial >();
testimonials.Add(new Testimonial {1} ); 
testimonials.Add(new Testimonial {2} );
testimonials.Add(new Testimonial {2} ); 
testimonials.Add(new Testimonial {3} );
testimonials.Add(new Testimonial {4} );

我将如何使用

testimonials.OrderBy<>

为了让它随机?

3 个答案:

答案 0 :(得分:7)

这是解决方案。

public static List<T> RandomizeGenericList<T>(IList<T> originalList)
{
    List<T> randomList = new List<T>();
    Random random = new Random();
    T value = default(T);

    //now loop through all the values in the list
    while (originalList.Count() > 0)
    {
        //pick a random item from th original list
        var nextIndex = random.Next(0, originalList.Count());
        //get the value for that random index
        value = originalList[nextIndex];
        //add item to the new randomized list
        randomList.Add(value);
        //remove value from original list (prevents
        //getting duplicates
        originalList.RemoveAt(nextIndex);
    }

    //return the randomized list
    return randomList;
}

来源链接:http://www.dreamincode.net/code/snippet4233.htm

此方法将随机化C#

中的任何通用列表

答案 1 :(得分:5)

var random = new Random(unchecked((int) (DateTime.Now.Ticks));

var randomList = testimonials.OrderBy(t => random.Next(100));

答案 2 :(得分:1)

Justin Niessner的解决方案简单而有效(我会给出的解决方案),但它是NlogN的复杂性。如果性能很重要,你可以使用Fischer-Yates-Durstenfeld shuffle在线性时间内对列表进行洗牌。看看这个问题:An extension method on IEnumerable needed for shuffling