Monday, September 20, 2010

IEnumerable.Exclude (Remove) extension

   Sometimes it can be useful to exclude one or more elements from a collection basing on a defined rule. I have written simple extension method for these purposes. Just specify the rule as an input parameter and receive resulting collection on the output.

The method:
         public static IEnumerable Exclude(this IEnumerable enumerable, 
            Func func)
        {
            if (func == null)
                throw new ArgumentNullException("func");

            var inputArray = enumerable.ToArray();
            var list = new List(enumerable);
            for (var i = 0; i < inputArray.Count(); i++)
            {
                if (func(inputArray[i]))
                    list.Remove(inputArray[i]);
            }
            return list;
        }
Unit tests:
        [Test]
        public void IEnumerable_Exclude_Works_For_Integers()
        {
            var a = new [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            var b = a.Exclude(i => i % 2 == 0);
            Assert.AreEqual(new[] {1, 3, 5, 7, 9}, b);
        }

        [Test]
        public void IEnumerable_Exclude_Works_For_DateTime()
        {
            var a = new[]
                        {
                            new DateTime(1900, 01, 01),
                            new DateTime(2000, 12, 31),
                            new DateTime(2035, 10, 01)
                        };
            var b = a.Exclude(d => d.Year >= 2000);
            Assert.AreEqual(new[] { new DateTime(1900, 01, 01) }, b);
        }

        [Test]
        public void IEnumerable_Exclude_Works_For_String()
        {
            var a = new[]
                        {
                            "The", "quick", "brown", "fox", 
                            "jumps", "over", "the", "lazy", "dog"
                        };
            var b = a.Exclude(s => s.Length > 4);
            Assert.AreEqual(new[] {"The", "fox", "over", "the", "lazy", "dog"}, b);
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void IEnumerable_Exclude_ThrowsException_If_FuncDelegate_IsNull()
        {
            var a = new[] { "ooo", "OOO", "ooo"};
            a.Exclude(null);
        }
Test results:

1 comment:

plotnick said...

nice.