分组

    class GroupTest {
        static void Main(string[] args) {
            List<int> src = new List<int> { 1, 5, 11, 22, 4, 3 };

            List<List<int>> gs = Split<int>(src, (current, next) => { return (current < 10 && next < 10); });
            //List<List<int>> gs = Split<int>(src, (current, next) => { return (current < 10 && next < 10) || (current >= 10 && next >= 10); });


            foreach (var each in gs) {
                List<string> t = new List<string>();
                each.ForEach(e => t.Add(e.ToString()));
                Console.WriteLine(string.Join(" ", t.ToArray()));
            }

            Console.WriteLine("== End ==");
            Console.ReadKey();
        }

        private static List<List<T>> Split<T>(List<T> src, Condition<T> condition) {
            List<List<T>> result = new List<List<T>>();

            List<T> current = new List<T>();
            for (int i = 0; i < src.Count; ++i) {
                T cur = src[i];
                T next = default(T);
                if (i < src.Count - 1) { next = src[i + 1]; }

                current.Add(cur);
                if (src.Count == i + 1 || !condition(cur, next)) {
                    result.Add(current);
                    current = new List<T>();
                }
            }

            return result;
        }
    }

    delegate bool Condition<T>(T current, T next);

posted on 2008-12-05 13:21  cjfwu  阅读(414)  评论(0)    收藏  举报

导航