Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
31 changes: 31 additions & 0 deletions ShittyLINQ/DefaultIfEmpty.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you get rid of the System.Text import?


namespace ShittyLINQ
{
public static partial class Extensions
{
public static IEnumerable<T> DefaultIfEmpty<T>(this IEnumerable<T> source)
{
return DefaultIfEmpty(source, default(T));
}

public static IEnumerable<T> DefaultIfEmpty<T>(this IEnumerable<T> self, T defaultValue)
{
if (self == null) throw new ArgumentNullException();
if (self.Count() <= 0)
{
yield return defaultValue;
}
else
{
var iterator = self.GetEnumerator();
while (iterator.MoveNext())
{
yield return iterator.Current;
}
}
}
}
}
43 changes: 43 additions & 0 deletions ShittyLinqTests/DefaultIfEmptyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ShittyLINQ;
using Enumerable = System.Linq.Enumerable;

namespace ShittyTests
{
[TestClass]
public class DefaultIfEmptyTests
{
[TestMethod]
public void Default_NotEmpty()
{
int[] source = { 1, 2, 3 };
int[] expectedResult = { 1, 2, 3 };

var result = source.DefaultIfEmpty(0);
Assert.IsTrue(Enumerable.SequenceEqual(expectedResult, result));
}

[TestMethod]
public void Default_Empty()
{
int[] source = { };
int[] expectedResult = { 0 };

var result = source.DefaultIfEmpty(0);
Assert.IsTrue(Enumerable.SequenceEqual(expectedResult, result));
}

[TestMethod]
public void Default_EnumerableNull()
{
int[] source = null;
int[] expectedResult = { 0 };

var result = source.DefaultIfEmpty(0);
Assert.IsTrue(Enumerable.SequenceEqual(expectedResult, result));
}
}
}