瀏覽代碼

Align ElementAt behavior with synchronous LINQ.

Bart De Smet 7 年之前
父節點
當前提交
46668196a3
共有 1 個文件被更改,包括 20 次插入25 次删除
  1. 20 25
      Ix.NET/Source/System.Linq.Async/System/Linq/Operators/ElementAt.cs

+ 20 - 25
Ix.NET/Source/System.Linq.Async/System/Linq/Operators/ElementAt.cs

@@ -22,22 +22,13 @@ namespace System.Linq
         {
             if (source == null)
                 throw Error.ArgumentNull(nameof(source));
-            if (index < 0)
-                throw Error.ArgumentOutOfRange(nameof(index));
 
             return ElementAtCore(source, index, cancellationToken);
         }
 
         private static async Task<TSource> ElementAtCore<TSource>(IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
         {
-            if (source is IList<TSource> list)
-            {
-                if (index < list.Count)
-                {
-                    return list[index];
-                }
-            }
-            else if (source is IAsyncPartition<TSource> p)
+            if (source is IAsyncPartition<TSource> p)
             {
                 var first = await p.TryGetElementAsync(index, cancellationToken).ConfigureAwait(false);
 
@@ -45,30 +36,34 @@ namespace System.Linq
                 {
                     return first.Value;
                 }
-                else
-                {
-                    throw Error.ArgumentOutOfRange(nameof(index));
-                }
             }
             else
             {
-                var e = source.GetAsyncEnumerator(cancellationToken);
+                if (source is IList<TSource> list)
+                {
+                    return list[index];
+                }
 
-                try
+                if (index >= 0)
                 {
-                    while (await e.MoveNextAsync().ConfigureAwait(false))
+                    var e = source.GetAsyncEnumerator(cancellationToken);
+
+                    try
                     {
-                        if (index == 0)
+                        while (await e.MoveNextAsync().ConfigureAwait(false))
                         {
-                            return e.Current;
-                        }
+                            if (index == 0)
+                            {
+                                return e.Current;
+                            }
 
-                        index--;
+                            index--;
+                        }
+                    }
+                    finally
+                    {
+                        await e.DisposeAsync().ConfigureAwait(false);
                     }
-                }
-                finally
-                {
-                    await e.DisposeAsync().ConfigureAwait(false);
                 }
             }