如何获取列表并按随机顺序进行排序?
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<>为了让它变得随机化?
发布于 2011-06-09 22:46:24
这就是解决方案。
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#中的任何泛型列表
发布于 2011-06-09 22:44:57
var random = new Random(unchecked((int) (DateTime.Now.Ticks));
var randomList = testimonials.OrderBy(t => random.Next(100));发布于 2011-06-09 22:57:12
Justin Niessner的解决方案简单而有效(这也是我想给出的解决方案),但它是NlogN的复杂性。如果性能很重要,您可以使用Fischer-Yates-Durstenfeld混洗在线性时间内对列表进行混洗。看一下这个问题:An extension method on IEnumerable needed for shuffling
https://stackoverflow.com/questions/6294671
复制相似问题