diff --git a/ShittyLINQ/TakeLast.cs b/ShittyLINQ/TakeLast.cs new file mode 100644 index 0000000..503a067 --- /dev/null +++ b/ShittyLINQ/TakeLast.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ShittyLINQ +{ + public static partial class Extensions + { + public static IEnumerable TakeLast(this IEnumerable self, int count) + { + if (self == null) throw new ArgumentNullException(); + + var numberElements = self.Count(); + + if (numberElements < count) throw new ArgumentOutOfRangeException(); + + var index = 0; + + foreach (T item in self) + { + if(index >= numberElements - count) + { + yield return item; + } + index++; + } + } + } +} diff --git a/ShittyLinqTests/TakeLastTests.cs b/ShittyLinqTests/TakeLastTests.cs new file mode 100644 index 0000000..0f66b5a --- /dev/null +++ b/ShittyLinqTests/TakeLastTests.cs @@ -0,0 +1,53 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using ShittyLINQ; +using System; +using System.Collections.Generic; + +namespace ShittyTests +{ + [TestClass] + public class TakeLastTests + { + [TestMethod] + public void When_Count_Is_Greather_Than_Element_In_List_Then_Throw_OutOfRange_Exception() + { + var list = new List { 1, 2, 3, 4 }; + + Assert.ThrowsException(() => list.TakeLast(5).ToList()); + } + + [TestMethod] + public void When_List_Is_Null_Then_Throw_Exception() + { + IEnumerable list = null; + + Assert.ThrowsException(() => list.TakeLast(5).ToList()); + } + + [TestMethod] + public void When_Take_Last_Five_Elements_Then_Should_Return_List_Of_Five() + { + var list = new List { 1, 2, 3, 4, 5, 6, 7 }; + var expectedList = new List { 3, 4, 5, 6, 7 }; + + var lastFiveElements = list.TakeLast(5).ToList(); + + Assert.IsTrue(lastFiveElements.Count == 5); + CollectionAssert.AreEqual(expectedList, lastFiveElements); + + } + + [TestMethod] + public void When_Take_Last_Five_Elements_In_List_Of_Five_Then_Should_Return_Same_List() + { + var list = new List { 3, 4, 5, 6, 7 }; + var expectedList = new List { 3, 4, 5, 6, 7 }; + + var lastFiveElements = list.TakeLast(5).ToList(); + + Assert.IsTrue(lastFiveElements.Count == 5); + CollectionAssert.AreEqual(expectedList, lastFiveElements); + + } + } +}