Skip to content

Commit 6f00630

Browse files
authored
Merge pull request #216 from mobile46/master
[FirstOrDefault] Fix bug
2 parents 1f29e36 + 3c27f05 commit 6f00630

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

src/StructLinq.Tests/FirstOrDefaultTests.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ public void ShouldReturnDefaultZeroAlloc()
4040
StructEnumerable.Empty<int>().FirstOrDefault(x=>x).Should().Be(default);
4141
}
4242

43-
4443
[Fact]
4544
public void ShouldReturnFirstElementWithFunc()
4645
{
@@ -62,5 +61,16 @@ public void ShouldReturnFirstElementWithFuncZeroAlloc()
6261
.Should()
6362
.Be(6);
6463
}
64+
65+
[Fact]
66+
public void ShouldReturnDefaultValue()
67+
{
68+
var array = Enumerable.Range(0, 10)
69+
.ToArray()
70+
.ToStructEnumerable()
71+
.FirstOrDefault(x => x == 11)
72+
.Should()
73+
.Be(default);
74+
}
6575
}
6676
}

src/StructLinq/First/StructCollection.First.cs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,12 @@ public static bool TryFirst<T, TCollection, TEnumerator>(this TCollection collec
105105
return false;
106106
for (int i = 0; i < collection.Count; i++)
107107
{
108-
first = collection.Get(i);
109-
if (predicate(first))
108+
var current = collection.Get(i);
109+
if (predicate(current))
110+
{
111+
first = current;
110112
return true;
113+
}
111114
}
112115
return false;
113116
}
@@ -120,9 +123,12 @@ public static bool TryFirst<T, TEnumerator>(this IStructCollection<T, TEnumerato
120123
return false;
121124
for (int i = 0; i < collection.Count; i++)
122125
{
123-
first = collection.Get(i);
124-
if (predicate(first))
126+
var current = collection.Get(i);
127+
if (predicate(current))
128+
{
129+
first = current;
125130
return true;
131+
}
126132
}
127133
return false;
128134
}
@@ -137,9 +143,12 @@ public static bool TryFirst<T, TCollection, TEnumerator, TFunc>(this TCollection
137143
return false;
138144
for (int i = 0; i < collection.Count; i++)
139145
{
140-
first = collection.Get(i);
146+
var current = collection.Get(i);
141147
if (predicate.Eval(first))
148+
{
149+
first = current;
142150
return true;
151+
}
143152
}
144153
return false;
145154
}

0 commit comments

Comments
 (0)