Source

Inside.Util / ListExtension.cs

Full commit
using System;
using System.Collections;
using System.Collections.Generic;

namespace Inside.Util {
	public static class ListExtension {
		/// <summary>
		/// 从列表中随机选择元素。
		/// </summary>
		public static T[] RandomSelect<T>(this IList src, int count = 6) {
			if(null == src) {
				throw new ArgumentNullException("src");
			}

			if(src.Count <= count) {
				throw new ArgumentException("集合的长度必须大于选择的个数。", "count");
			}

			var result = new List<T>();
			for(int i = 0;i < count;++i) {
				result.Add((T)src[Math.Abs(Guid.NewGuid().GetHashCode()) % src.Count]);
			}

			return result.ToArray();
		}

		/// <summary>
		/// 打乱列表中元素的次序。
		/// </summary>
		public static void Shuffle(this IList src) {
			if(null == src || 0 == src.Count) {
				return;
			}

			Object tmpForSwap = null;
			int tmpCursorIndex = 0;

			for(int cursorIndex = src.Count - 1;0 != cursorIndex;--cursorIndex) {
				tmpCursorIndex = Math.Abs(Guid.NewGuid().GetHashCode()) % cursorIndex;

				tmpForSwap = src[cursorIndex];
				src[cursorIndex] = src[tmpCursorIndex];
				src[tmpCursorIndex] = tmpForSwap;
			}
		}
	}
}