日期:2014-05-20 浏览次数:20792 次
void Main() { List<int> ints=new List<int>{10,100,101,102,150,300,301}; var list=ints.OrderBy(i=>i).ToList(); var temp=new List<List<int>>(); var query=list.Aggregate((m,n)=> { if(temp.Count()>0) { if(temp.Last().Last()==n-1) { temp.Last().Add(n); } else if(m==n-1) { temp.Add(new List<int>{m,n}); } } else { if(m==n-1) { temp.Add(new List<int>{m,n}); } } return n; } ); var result=from t in temp select new {Key=t.First(),Count=t.Count()-1}; result.ToList().ForEach(r=>Console.WriteLine("{0}\t{1}",r.Key,r.Count)); /* 100 2 300 1 */ }
------解决方案--------------------
var list1 = new List<int>(); int temp = 0; var query = intss.Select(ints => { list1 = new List<int>(); ints.Aggregate((s, n) => { if ((s + 1) == n) { if (temp == 0) temp = s; list1.Add(temp); } else { temp = 0; } return n; }); return list1.GroupBy(g => g).Select(s => new { key = s.Key, count = s.Count() }); }); foreach (var item in query) Console.WriteLine(string.Join("", item.Select(s => string.Format("[{0},{1}]", s.key, s.count)).ToArray()));