ASP.net列表随机排序

bre*_*njt 1 asp.net random asp.net-mvc

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

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} );
Run Code Online (Sandbox Code Playgroud)

我该怎么用

testimonials.OrderBy<>
Run Code Online (Sandbox Code Playgroud)

为了让它随机?

Moh*_*lam 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;
}
Run Code Online (Sandbox Code Playgroud)

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

此方法将随机化C#中的任何通用列表

  • 您应该在此处包含解决方案的相关部分,并将链接作为参考. (2认同)

Jus*_*ner 5

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

var randomList = testimonials.OrderBy(t => random.Next(100));
Run Code Online (Sandbox Code Playgroud)