gpt4 book ai didi

ASP.net 列表随机排序

转载 作者:行者123 更新时间:2023-12-05 08:21:27 26 4
gpt4 key购买 nike

如何获取一个列表并随机排序?

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<>

为了让它随机?

最佳答案

这是解决方案。

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# 中的任何泛型列表

关于ASP.net 列表随机排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com