Linq Orderby random ThreadSafe for use in ASP.NET

前端 未结 5 1912
春和景丽
春和景丽 2020-11-29 05:23

i\'m using Asp.net MVC with Sharp Architecture.

I have this code:

return _repositoryKeyWord.FindAll(x => x.Category.Id == idCAtegory)
                     


        
5条回答
  •  再見小時候
    2020-11-29 06:06

    Probably best to write your own extension method to do it.

    public static class Extensions
    {
        static readonly Random random = new Random();
    
        public static IEnumerable Shuffle(this IEnumerable items)
        {
            return Shuffle(items, random);
        }
    
        public static IEnumerable Shuffle(this IEnumerable items, Random random)
        {
            // Un-optimized algorithm taken from
            // http://en.wikipedia.org/wiki/Knuth_shuffle#The_modern_algorithm
            List list = new List(items);
            for (int i = list.Count - 1; i >= 1; i--) 
            {
                int j = random.Next(0, i);
                T temp = list[i];
                list[i] = list[j];
                list[j] = temp;
            }
            return list;
        }
    }
    

提交回复
热议问题