趣味编程(一)
1、需求:找出一个给定字符串中每个字符及其重复次数,同时获取出重复次数最多的字符。
public static T MaxElement<T, TCompare>(this IEnumerable<T> collection, Func<T, TCompare> func) where TCompare : IComparable<TCompare> { T maxItem = default(T); TCompare maxValue = default(TCompare); foreach (var item in collection) { TCompare temp = func(item); if (maxItem == null || temp.CompareTo(maxValue) > 0) { maxValue = temp; maxItem = item; } } return maxItem; }
string findStr = "Beijing"; var rm = findStr.ToCharArray().GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).MaxElement(r => r.Count);
2、需求:生成不重复的随机数并排序。
public static IList<int> GetRandoms(int min, int max, int length) { IList<int> rlist = new List<int>(); int index = 1; int seed = new Random().Next(); while (index < length) { var random = new Random(seed++).Next(min, max); if (!rlist.Contains(random)) rlist.Add(random); index = rlist.Count(); Console.WriteLine(index); } return rlist; }
List<int> rlist = GetRandoms(10, 99, 20).ToList(); rlist.Sort((x, y) => Math.Sign(x - y));