Skip to content

Commit c31daa7

Browse files
committed
First as enumerable extensions
SVN: trunk@5317
1 parent 920e2e8 commit c31daa7

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

src/NHibernate.Test/NHibernate.Test.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -581,6 +581,7 @@
581581
<Compile Include="TypesTest\XmlDocClass.cs" />
582582
<Compile Include="TypesTest\XmlDocTypeFixture.cs" />
583583
<Compile Include="UtilityTest\EnumerableExtensionsTests\AnyExtensionTests.cs" />
584+
<Compile Include="UtilityTest\EnumerableExtensionsTests\FirstExtensionTests.cs" />
584585
<Compile Include="UtilityTest\ReflectionHelperIsMethodOfTests.cs" />
585586
<Compile Include="UtilityTest\ReflectionHelperTest.cs" />
586587
<Compile Include="Linq\RegresstionTests.cs" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System;
2+
using System.Collections;
3+
using NHibernate.Util;
4+
using NUnit.Framework;
5+
using SharpTestsEx;
6+
7+
namespace NHibernate.Test.UtilityTest.EnumerableExtensionsTests
8+
{
9+
public class FirstExtensionTests
10+
{
11+
[Test]
12+
public void WhenNullThenThenThrows()
13+
{
14+
Executing.This(() => ((IEnumerable)null).First()).Should().Throw<ArgumentNullException>();
15+
}
16+
17+
[Test]
18+
public void WhenHasElementsThenReturnFirst()
19+
{
20+
(new[] { 2, 1 }).First().Should().Be(2);
21+
}
22+
23+
[Test]
24+
public void WhenEmptyThenThrowsInvalidOperation()
25+
{
26+
Executing.This(() => (new object[0]).First()).Should().Throw<InvalidOperationException>();
27+
}
28+
}
29+
}

src/NHibernate/Util/EnumerableExtensions.cs

+27
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,33 @@ public static bool Any(this IEnumerable source)
2121
return false;
2222
}
2323

24+
public static object First(this IEnumerable source)
25+
{
26+
if (source == null)
27+
{
28+
throw new ArgumentNullException("source");
29+
}
30+
IList collection = source as IList;
31+
if (collection != null)
32+
{
33+
if (collection.Count > 0)
34+
{
35+
return collection[0];
36+
}
37+
}
38+
else
39+
{
40+
using (DisposableEnumerator enumerator = source.GetDisposableEnumerator())
41+
{
42+
if (enumerator.MoveNext())
43+
{
44+
return enumerator.Current;
45+
}
46+
}
47+
}
48+
throw new InvalidOperationException("Sequence contains no elements");
49+
}
50+
2451
private static DisposableEnumerator GetDisposableEnumerator(this IEnumerable source)
2552
{
2653
return new DisposableEnumerator(source);

0 commit comments

Comments
 (0)