Skip to content

Commit

Permalink
Implement dotnet#28776: LINQ APIs for index and range. Code review up…
Browse files Browse the repository at this point in the history
…date.
  • Loading branch information
Dixin committed Feb 7, 2021
1 parent e9922bf commit 52b8617
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 19 deletions.
13 changes: 6 additions & 7 deletions src/libraries/System.Linq/src/System/Linq/ElementAt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,12 @@ public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, Index
return source.ElementAt(index.Value);
}

if (TryGetElementAt(source, index.Value, out TSource? result))
if (!TryGetElementAt(source, index.Value, out TSource? result))
{
return result;
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}

ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
return default;
return result!;
}

public static TSource? ElementAtOrDefault<TSource>(this IEnumerable<TSource> source, int index)
Expand Down Expand Up @@ -150,7 +149,7 @@ public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, Index
return result;
}

private static bool TryGetElementAt<TSource>(IEnumerable<TSource> source, int indexFromEnd, [NotNullWhen(true)] out TSource? result)
private static bool TryGetElementAt<TSource>(IEnumerable<TSource> source, int indexFromEnd, [MaybeNullWhen(false)] out TSource? result)
{
Debug.Assert(indexFromEnd >= 0);

Expand Down Expand Up @@ -184,7 +183,7 @@ private static bool TryGetElementAt<TSource>(IEnumerable<TSource> source, int in
int count = list.Count;
if (indexFromEnd <= count)
{
result = list[count - indexFromEnd]!;
result = list[count - indexFromEnd];
return true;
}

Expand All @@ -211,7 +210,7 @@ private static bool TryGetElementAt<TSource>(IEnumerable<TSource> source, int in

if (queue.Count == indexFromEnd)
{
result = queue.Dequeue()!;
result = queue.Dequeue();
return true;
}

Expand Down
14 changes: 2 additions & 12 deletions src/libraries/System.Linq/src/System/Linq/Take.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> sourc

if (isStartIndexFromEnd)
{
if (startIndex == 0 || isEndIndexFromEnd && endIndex >= startIndex)
if (startIndex == 0 || (isEndIndexFromEnd && endIndex >= startIndex))
{
return Empty<TSource>();
}
Expand Down Expand Up @@ -123,13 +123,8 @@ private static IEnumerable<TSource> TakeIterator<TSource>(
}
else
{
if (!e.MoveNext())
{
yield break;
}

int index = 0;
while (index < startIndex)
while (index <= startIndex)
{
if (!e.MoveNext())
{
Expand All @@ -142,11 +137,6 @@ private static IEnumerable<TSource> TakeIterator<TSource>(
}
}

if (index != startIndex)
{
yield break;
}

if (isEndIndexFromEnd)
{
if (endIndex > 0)
Expand Down

0 comments on commit 52b8617

Please sign in to comment.