среда, 31 октября 2007 г.

Баловство с С# 3.0

Смысла именно в этом нет, поскольку то же самое можно через Linq. Но сам факт того что это можно сделать приятен.

namespace alogrithm

{

    public static class collections

    {

        public delegate void WithFunctor<S>(S elem);

        public delegate bool Predicate<S>(S elem);

 

        public static IEnumerable<S> find_if<S>(this IEnumerable<S> list, Predicate<S> predicate)

        {

            foreach (S elem in list)

                if(predicate(elem))

                    yield return elem;

        }

        public static void with<S>(this IEnumerable<S> source, WithFunctor<S> action)

        {

            foreach (S elem in source)

                action(elem);

        }

    }

    class Testing

    {

        static public void test()

        {

 

            int[] numbers = new int[] { 1, 2, 3, 4, 5 };

            numbers.find_if( (x) => { return x > 3 ? true : false; }).with( (x) => { System.Console.WriteLine(x); });

        }

    }

}



ЗЫ: но так все равно лучше...

            var numberGroups =

                from n in numbers

                group n by n % 5 into g

                select new { Remainder = g.Key, Numbers = g };