C# Net 合并int集合为字符串,如1,2,3,4,8 输出1~4,8
粘贴代码使用:
/// <summary> /// 合并int集合,如1,2,3,4,8 输出1~4,8 /// </summary> public static string MergeInts(IEnumerable<int> ints) { string CollectionNumberStr = string.Empty; List<string> CollectionNumberStrArr = new List<string>(); if (ints != null && ints.Count() > 0) { var query = ints.OrderBy(p => p).Aggregate<int, List<List<int>>>(null, (m, n) => { if (m == null) return new List<List<int>>() { new List<int>() { n } }; if (m.Last().Last() != n - 1) m.Add(new List<int>() { n }); else m.Last().Add(n); return m; }); query.ForEach(p => { int First = p.First(); int Last = p.Last(); if (First == Last) CollectionNumberStrArr.Add(First.ToString()); else CollectionNumberStrArr.Add(First + "~" + Last); }); CollectionNumberStr = CollectionNumberStr.Trim(); } return CollectionNumberStr = string.Join("、", CollectionNumberStrArr); }