Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions ShittyLINQ/TakeLast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace ShittyLINQ
{
public static partial class Extensions
{
public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> 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++;
}
}
}
}
53 changes: 53 additions & 0 deletions ShittyLinqTests/TakeLastTests.cs
Original file line number Diff line number Diff line change
@@ -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<int> { 1, 2, 3, 4 };

Assert.ThrowsException<ArgumentOutOfRangeException>(() => list.TakeLast(5).ToList());
}

[TestMethod]
public void When_List_Is_Null_Then_Throw_Exception()
{
IEnumerable<int> list = null;

Assert.ThrowsException<ArgumentNullException>(() => list.TakeLast(5).ToList());
}

[TestMethod]
public void When_Take_Last_Five_Elements_Then_Should_Return_List_Of_Five()
{
var list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
var expectedList = new List<int> { 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<int> { 3, 4, 5, 6, 7 };
var expectedList = new List<int> { 3, 4, 5, 6, 7 };

var lastFiveElements = list.TakeLast(5).ToList();

Assert.IsTrue(lastFiveElements.Count == 5);
CollectionAssert.AreEqual(expectedList, lastFiveElements);

}
}
}