12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- /// <summary>
- ///
- /// </summary>
- public partial class Utils
- {
- }
- /// <summary>
- /// 扩展下Linq,增加一个取随机值方法. wanggangzero@vip.qq.coms
- /// </summary>
- public static class LinqExt
- {
-
- static Random r = new Random(Guid.NewGuid().GetHashCode()); // 随机种子
- /// <summary>
- /// 从集合中随机取一批数据
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="source"></param>
- /// <param name="count"></param>
- /// <returns></returns>
- public static IEnumerable<T> Random<T>(this IEnumerable<T> source, int? count = null)
- {
- return count.HasValue ? source.OrderBy(_ => r.Next()).Take(count.Value) : source.OrderBy(_ => r.Next());
- }
- /// <summary>
- /// 仿PHP的implode函数
- /// </summary>
- /// <param name="source"></param>
- /// <param name="glue"></param>
- /// <returns></returns>
- public static string Implode(this IEnumerable<string> source, string glue = "")
- {
- var sb = new StringBuilder();
- var n = source.Count();
- int i = 0;
- source.ToList().ForEach(s => sb.Append((++i < n) ? s + glue : s));
- return sb.ToString();
- }
- public static string[] Explode(this string strSource, string seperator = ""){
- return strSource.Split(new string[] { seperator }, StringSplitOptions.RemoveEmptyEntries);
- }
- }
|