You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3047 lines
86 KiB

  1. 
  2. #if NET20
  3. #region License, Terms and Author(s)
  4. //
  5. // LINQBridge
  6. // Copyright (c) 2007-9 Atif Aziz, Joseph Albahari. All rights reserved.
  7. //
  8. // Author(s):
  9. //
  10. // Atif Aziz, http://www.raboof.com
  11. //
  12. // This library is free software; you can redistribute it and/or modify it
  13. // under the terms of the New BSD License, a copy of which should have
  14. // been delivered along with this distribution.
  15. //
  16. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  17. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  18. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  19. // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  20. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  22. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. //
  28. #endregion
  29. using System;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Diagnostics;
  33. using System.Globalization;
  34. using Newtonsoft.Json.Serialization;
  35. namespace Newtonsoft.Json.Utilities.LinqBridge
  36. {
  37. /// <summary>
  38. /// Provides a set of static (Shared in Visual Basic) methods for
  39. /// querying objects that implement <see cref="IEnumerable{T}" />.
  40. /// </summary>
  41. internal static partial class Enumerable
  42. {
  43. /// <summary>
  44. /// Returns the input typed as <see cref="IEnumerable{T}"/>.
  45. /// </summary>
  46. public static IEnumerable<TSource> AsEnumerable<TSource>(IEnumerable<TSource> source)
  47. {
  48. return source;
  49. }
  50. /// <summary>
  51. /// Returns an empty <see cref="IEnumerable{T}"/> that has the
  52. /// specified type argument.
  53. /// </summary>
  54. public static IEnumerable<TResult> Empty<TResult>()
  55. {
  56. return Sequence<TResult>.Empty;
  57. }
  58. /// <summary>
  59. /// Converts the elements of an <see cref="IEnumerable"/> to the
  60. /// specified type.
  61. /// </summary>
  62. public static IEnumerable<TResult> Cast<TResult>(
  63. this IEnumerable source)
  64. {
  65. CheckNotNull(source, "source");
  66. var servesItself = source as IEnumerable<TResult>;
  67. if (servesItself != null
  68. && (!(servesItself is TResult[]) || servesItself.GetType().GetElementType() == typeof(TResult)))
  69. {
  70. return servesItself;
  71. }
  72. return CastYield<TResult>(source);
  73. }
  74. private static IEnumerable<TResult> CastYield<TResult>(
  75. IEnumerable source)
  76. {
  77. foreach (var item in source)
  78. yield return (TResult) item;
  79. }
  80. /// <summary>
  81. /// Filters the elements of an <see cref="IEnumerable"/> based on a specified type.
  82. /// </summary>
  83. public static IEnumerable<TResult> OfType<TResult>(
  84. this IEnumerable source)
  85. {
  86. CheckNotNull(source, "source");
  87. return OfTypeYield<TResult>(source);
  88. }
  89. private static IEnumerable<TResult> OfTypeYield<TResult>(
  90. IEnumerable source)
  91. {
  92. foreach (var item in source)
  93. if (item is TResult)
  94. yield return (TResult) item;
  95. }
  96. /// <summary>
  97. /// Generates a sequence of integral numbers within a specified range.
  98. /// </summary>
  99. /// <param name="start">The value of the first integer in the sequence.</param>
  100. /// <param name="count">The number of sequential integers to generate.</param>
  101. public static IEnumerable<int> Range(int start, int count)
  102. {
  103. if (count < 0)
  104. throw new ArgumentOutOfRangeException("count", count, null);
  105. var end = (long) start + count;
  106. if (end - 1 >= int.MaxValue)
  107. throw new ArgumentOutOfRangeException("count", count, null);
  108. return RangeYield(start, end);
  109. }
  110. private static IEnumerable<int> RangeYield(int start, long end)
  111. {
  112. for (var i = start; i < end; i++)
  113. yield return i;
  114. }
  115. /// <summary>
  116. /// Generates a sequence that contains one repeated value.
  117. /// </summary>
  118. public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
  119. {
  120. if (count < 0) throw new ArgumentOutOfRangeException("count", count, null);
  121. return RepeatYield(element, count);
  122. }
  123. private static IEnumerable<TResult> RepeatYield<TResult>(TResult element, int count)
  124. {
  125. for (var i = 0; i < count; i++)
  126. yield return element;
  127. }
  128. /// <summary>
  129. /// Filters a sequence of values based on a predicate.
  130. /// </summary>
  131. public static IEnumerable<TSource> Where<TSource>(
  132. this IEnumerable<TSource> source,
  133. Func<TSource, bool> predicate)
  134. {
  135. CheckNotNull(source, "source");
  136. CheckNotNull(predicate, "predicate");
  137. return WhereYield(source, predicate);
  138. }
  139. private static IEnumerable<TSource> WhereYield<TSource>(
  140. IEnumerable<TSource> source,
  141. Func<TSource, bool> predicate)
  142. {
  143. foreach (var item in source)
  144. if (predicate(item))
  145. yield return item;
  146. }
  147. /// <summary>
  148. /// Filters a sequence of values based on a predicate.
  149. /// Each element's index is used in the logic of the predicate function.
  150. /// </summary>
  151. public static IEnumerable<TSource> Where<TSource>(
  152. this IEnumerable<TSource> source,
  153. Func<TSource, int, bool> predicate)
  154. {
  155. CheckNotNull(source, "source");
  156. CheckNotNull(predicate, "predicate");
  157. return WhereYield(source, predicate);
  158. }
  159. private static IEnumerable<TSource> WhereYield<TSource>(
  160. IEnumerable<TSource> source,
  161. Func<TSource, int, bool> predicate)
  162. {
  163. var i = 0;
  164. foreach (var item in source)
  165. if (predicate(item, i++))
  166. yield return item;
  167. }
  168. /// <summary>
  169. /// Projects each element of a sequence into a new form.
  170. /// </summary>
  171. public static IEnumerable<TResult> Select<TSource, TResult>(
  172. this IEnumerable<TSource> source,
  173. Func<TSource, TResult> selector)
  174. {
  175. CheckNotNull(source, "source");
  176. CheckNotNull(selector, "selector");
  177. return SelectYield(source, selector);
  178. }
  179. private static IEnumerable<TResult> SelectYield<TSource, TResult>(
  180. IEnumerable<TSource> source,
  181. Func<TSource, TResult> selector)
  182. {
  183. foreach (var item in source)
  184. yield return selector(item);
  185. }
  186. /// <summary>
  187. /// Projects each element of a sequence into a new form by
  188. /// incorporating the element's index.
  189. /// </summary>
  190. public static IEnumerable<TResult> Select<TSource, TResult>(
  191. this IEnumerable<TSource> source,
  192. Func<TSource, int, TResult> selector)
  193. {
  194. CheckNotNull(source, "source");
  195. CheckNotNull(selector, "selector");
  196. return SelectYield(source, selector);
  197. }
  198. private static IEnumerable<TResult> SelectYield<TSource, TResult>(
  199. IEnumerable<TSource> source,
  200. Func<TSource, int, TResult> selector)
  201. {
  202. var i = 0;
  203. foreach (var item in source)
  204. yield return selector(item, i++);
  205. }
  206. /// <summary>
  207. /// Projects each element of a sequence to an <see cref="IEnumerable{T}" />
  208. /// and flattens the resulting sequences into one sequence.
  209. /// </summary>
  210. public static IEnumerable<TResult> SelectMany<TSource, TResult>(
  211. this IEnumerable<TSource> source,
  212. Func<TSource, IEnumerable<TResult>> selector)
  213. {
  214. CheckNotNull(selector, "selector");
  215. return source.SelectMany((item, i) => selector(item));
  216. }
  217. /// <summary>
  218. /// Projects each element of a sequence to an <see cref="IEnumerable{T}" />,
  219. /// and flattens the resulting sequences into one sequence. The
  220. /// index of each source element is used in the projected form of
  221. /// that element.
  222. /// </summary>
  223. public static IEnumerable<TResult> SelectMany<TSource, TResult>(
  224. this IEnumerable<TSource> source,
  225. Func<TSource, int, IEnumerable<TResult>> selector)
  226. {
  227. CheckNotNull(selector, "selector");
  228. return source.SelectMany(selector, (item, subitem) => subitem);
  229. }
  230. /// <summary>
  231. /// Projects each element of a sequence to an <see cref="IEnumerable{T}" />,
  232. /// flattens the resulting sequences into one sequence, and invokes
  233. /// a result selector function on each element therein.
  234. /// </summary>
  235. public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
  236. this IEnumerable<TSource> source,
  237. Func<TSource, IEnumerable<TCollection>> collectionSelector,
  238. Func<TSource, TCollection, TResult> resultSelector)
  239. {
  240. CheckNotNull(collectionSelector, "collectionSelector");
  241. return source.SelectMany((item, i) => collectionSelector(item), resultSelector);
  242. }
  243. /// <summary>
  244. /// Projects each element of a sequence to an <see cref="IEnumerable{T}" />,
  245. /// flattens the resulting sequences into one sequence, and invokes
  246. /// a result selector function on each element therein. The index of
  247. /// each source element is used in the intermediate projected form
  248. /// of that element.
  249. /// </summary>
  250. public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
  251. this IEnumerable<TSource> source,
  252. Func<TSource, int, IEnumerable<TCollection>> collectionSelector,
  253. Func<TSource, TCollection, TResult> resultSelector)
  254. {
  255. CheckNotNull(source, "source");
  256. CheckNotNull(collectionSelector, "collectionSelector");
  257. CheckNotNull(resultSelector, "resultSelector");
  258. return SelectManyYield(source, collectionSelector, resultSelector);
  259. }
  260. private static IEnumerable<TResult> SelectManyYield<TSource, TCollection, TResult>(
  261. this IEnumerable<TSource> source,
  262. Func<TSource, int, IEnumerable<TCollection>> collectionSelector,
  263. Func<TSource, TCollection, TResult> resultSelector)
  264. {
  265. var i = 0;
  266. foreach (var item in source)
  267. foreach (var subitem in collectionSelector(item, i++))
  268. yield return resultSelector(item, subitem);
  269. }
  270. /// <summary>
  271. /// Returns elements from a sequence as long as a specified condition is true.
  272. /// </summary>
  273. public static IEnumerable<TSource> TakeWhile<TSource>(
  274. this IEnumerable<TSource> source,
  275. Func<TSource, bool> predicate)
  276. {
  277. CheckNotNull(predicate, "predicate");
  278. return source.TakeWhile((item, i) => predicate(item));
  279. }
  280. /// <summary>
  281. /// Returns elements from a sequence as long as a specified condition is true.
  282. /// The element's index is used in the logic of the predicate function.
  283. /// </summary>
  284. public static IEnumerable<TSource> TakeWhile<TSource>(
  285. this IEnumerable<TSource> source,
  286. Func<TSource, int, bool> predicate)
  287. {
  288. CheckNotNull(source, "source");
  289. CheckNotNull(predicate, "predicate");
  290. return TakeWhileYield(source, predicate);
  291. }
  292. private static IEnumerable<TSource> TakeWhileYield<TSource>(
  293. this IEnumerable<TSource> source,
  294. Func<TSource, int, bool> predicate)
  295. {
  296. var i = 0;
  297. foreach (var item in source)
  298. if (predicate(item, i++))
  299. yield return item;
  300. else
  301. break;
  302. }
  303. private static class Futures<T>
  304. {
  305. public static readonly Func<T> Default = () => default(T);
  306. public static readonly Func<T> Undefined = () => { throw new InvalidOperationException(); };
  307. }
  308. /// <summary>
  309. /// Base implementation of First operator.
  310. /// </summary>
  311. private static TSource FirstImpl<TSource>(
  312. this IEnumerable<TSource> source,
  313. Func<TSource> empty)
  314. {
  315. CheckNotNull(source, "source");
  316. Debug.Assert(empty != null);
  317. var list = source as IList<TSource>; // optimized case for lists
  318. if (list != null)
  319. return list.Count > 0 ? list[0] : empty();
  320. using (var e = source.GetEnumerator()) // fallback for enumeration
  321. return e.MoveNext() ? e.Current : empty();
  322. }
  323. /// <summary>
  324. /// Returns the first element of a sequence.
  325. /// </summary>
  326. public static TSource First<TSource>(
  327. this IEnumerable<TSource> source)
  328. {
  329. return source.FirstImpl(Futures<TSource>.Undefined);
  330. }
  331. /// <summary>
  332. /// Returns the first element in a sequence that satisfies a specified condition.
  333. /// </summary>
  334. public static TSource First<TSource>(
  335. this IEnumerable<TSource> source,
  336. Func<TSource, bool> predicate)
  337. {
  338. return First(source.Where(predicate));
  339. }
  340. /// <summary>
  341. /// Returns the first element of a sequence, or a default value if
  342. /// the sequence contains no elements.
  343. /// </summary>
  344. public static TSource FirstOrDefault<TSource>(
  345. this IEnumerable<TSource> source)
  346. {
  347. return source.FirstImpl(Futures<TSource>.Default);
  348. }
  349. /// <summary>
  350. /// Returns the first element of the sequence that satisfies a
  351. /// condition or a default value if no such element is found.
  352. /// </summary>
  353. public static TSource FirstOrDefault<TSource>(
  354. this IEnumerable<TSource> source,
  355. Func<TSource, bool> predicate)
  356. {
  357. return FirstOrDefault(source.Where(predicate));
  358. }
  359. /// <summary>
  360. /// Base implementation of Last operator.
  361. /// </summary>
  362. private static TSource LastImpl<TSource>(
  363. this IEnumerable<TSource> source,
  364. Func<TSource> empty)
  365. {
  366. CheckNotNull(source, "source");
  367. var list = source as IList<TSource>; // optimized case for lists
  368. if (list != null)
  369. return list.Count > 0 ? list[list.Count - 1] : empty();
  370. using (var e = source.GetEnumerator())
  371. {
  372. if (!e.MoveNext())
  373. return empty();
  374. var last = e.Current;
  375. while (e.MoveNext())
  376. last = e.Current;
  377. return last;
  378. }
  379. }
  380. /// <summary>
  381. /// Returns the last element of a sequence.
  382. /// </summary>
  383. public static TSource Last<TSource>(
  384. this IEnumerable<TSource> source)
  385. {
  386. return source.LastImpl(Futures<TSource>.Undefined);
  387. }
  388. /// <summary>
  389. /// Returns the last element of a sequence that satisfies a
  390. /// specified condition.
  391. /// </summary>
  392. public static TSource Last<TSource>(
  393. this IEnumerable<TSource> source,
  394. Func<TSource, bool> predicate)
  395. {
  396. return Last(source.Where(predicate));
  397. }
  398. /// <summary>
  399. /// Returns the last element of a sequence, or a default value if
  400. /// the sequence contains no elements.
  401. /// </summary>
  402. public static TSource LastOrDefault<TSource>(
  403. this IEnumerable<TSource> source)
  404. {
  405. return source.LastImpl(Futures<TSource>.Default);
  406. }
  407. /// <summary>
  408. /// Returns the last element of a sequence that satisfies a
  409. /// condition or a default value if no such element is found.
  410. /// </summary>
  411. public static TSource LastOrDefault<TSource>(
  412. this IEnumerable<TSource> source,
  413. Func<TSource, bool> predicate)
  414. {
  415. return LastOrDefault(source.Where(predicate));
  416. }
  417. /// <summary>
  418. /// Base implementation of Single operator.
  419. /// </summary>
  420. private static TSource SingleImpl<TSource>(
  421. this IEnumerable<TSource> source,
  422. Func<TSource> empty)
  423. {
  424. CheckNotNull(source, "source");
  425. using (var e = source.GetEnumerator())
  426. {
  427. if (e.MoveNext())
  428. {
  429. var single = e.Current;
  430. if (!e.MoveNext())
  431. return single;
  432. throw new InvalidOperationException();
  433. }
  434. return empty();
  435. }
  436. }
  437. /// <summary>
  438. /// Returns the only element of a sequence, and throws an exception
  439. /// if there is not exactly one element in the sequence.
  440. /// </summary>
  441. public static TSource Single<TSource>(
  442. this IEnumerable<TSource> source)
  443. {
  444. return source.SingleImpl(Futures<TSource>.Undefined);
  445. }
  446. /// <summary>
  447. /// Returns the only element of a sequence that satisfies a
  448. /// specified condition, and throws an exception if more than one
  449. /// such element exists.
  450. /// </summary>
  451. public static TSource Single<TSource>(
  452. this IEnumerable<TSource> source,
  453. Func<TSource, bool> predicate)
  454. {
  455. return Single(source.Where(predicate));
  456. }
  457. /// <summary>
  458. /// Returns the only element of a sequence, or a default value if
  459. /// the sequence is empty; this method throws an exception if there
  460. /// is more than one element in the sequence.
  461. /// </summary>
  462. public static TSource SingleOrDefault<TSource>(
  463. this IEnumerable<TSource> source)
  464. {
  465. return source.SingleImpl(Futures<TSource>.Default);
  466. }
  467. /// <summary>
  468. /// Returns the only element of a sequence that satisfies a
  469. /// specified condition or a default value if no such element
  470. /// exists; this method throws an exception if more than one element
  471. /// satisfies the condition.
  472. /// </summary>
  473. public static TSource SingleOrDefault<TSource>(
  474. this IEnumerable<TSource> source,
  475. Func<TSource, bool> predicate)
  476. {
  477. return SingleOrDefault(source.Where(predicate));
  478. }
  479. /// <summary>
  480. /// Returns the element at a specified index in a sequence.
  481. /// </summary>
  482. public static TSource ElementAt<TSource>(
  483. this IEnumerable<TSource> source,
  484. int index)
  485. {
  486. CheckNotNull(source, "source");
  487. if (index < 0)
  488. throw new ArgumentOutOfRangeException("index", index, null);
  489. var list = source as IList<TSource>;
  490. if (list != null)
  491. return list[index];
  492. try
  493. {
  494. return source.SkipWhile((item, i) => i < index).First();
  495. }
  496. catch (InvalidOperationException) // if thrown by First
  497. {
  498. throw new ArgumentOutOfRangeException("index", index, null);
  499. }
  500. }
  501. /// <summary>
  502. /// Returns the element at a specified index in a sequence or a
  503. /// default value if the index is out of range.
  504. /// </summary>
  505. public static TSource ElementAtOrDefault<TSource>(
  506. this IEnumerable<TSource> source,
  507. int index)
  508. {
  509. CheckNotNull(source, "source");
  510. if (index < 0)
  511. return default(TSource);
  512. var list = source as IList<TSource>;
  513. if (list != null)
  514. return index < list.Count ? list[index] : default(TSource);
  515. return source.SkipWhile((item, i) => i < index).FirstOrDefault();
  516. }
  517. /// <summary>
  518. /// Inverts the order of the elements in a sequence.
  519. /// </summary>
  520. public static IEnumerable<TSource> Reverse<TSource>(
  521. this IEnumerable<TSource> source)
  522. {
  523. CheckNotNull(source, "source");
  524. return ReverseYield(source);
  525. }
  526. private static IEnumerable<TSource> ReverseYield<TSource>(IEnumerable<TSource> source)
  527. {
  528. var stack = new Stack<TSource>(source);
  529. foreach (var item in stack)
  530. yield return item;
  531. }
  532. /// <summary>
  533. /// Returns a specified number of contiguous elements from the start
  534. /// of a sequence.
  535. /// </summary>
  536. public static IEnumerable<TSource> Take<TSource>(
  537. this IEnumerable<TSource> source,
  538. int count)
  539. {
  540. return source.Where((item, i) => i < count);
  541. }
  542. /// <summary>
  543. /// Bypasses a specified number of elements in a sequence and then
  544. /// returns the remaining elements.
  545. /// </summary>
  546. public static IEnumerable<TSource> Skip<TSource>(
  547. this IEnumerable<TSource> source,
  548. int count)
  549. {
  550. return source.Where((item, i) => i >= count);
  551. }
  552. /// <summary>
  553. /// Bypasses elements in a sequence as long as a specified condition
  554. /// is true and then returns the remaining elements.
  555. /// </summary>
  556. public static IEnumerable<TSource> SkipWhile<TSource>(
  557. this IEnumerable<TSource> source,
  558. Func<TSource, bool> predicate)
  559. {
  560. CheckNotNull(predicate, "predicate");
  561. return source.SkipWhile((item, i) => predicate(item));
  562. }
  563. /// <summary>
  564. /// Bypasses elements in a sequence as long as a specified condition
  565. /// is true and then returns the remaining elements. The element's
  566. /// index is used in the logic of the predicate function.
  567. /// </summary>
  568. public static IEnumerable<TSource> SkipWhile<TSource>(
  569. this IEnumerable<TSource> source,
  570. Func<TSource, int, bool> predicate)
  571. {
  572. CheckNotNull(source, "source");
  573. CheckNotNull(predicate, "predicate");
  574. return SkipWhileYield(source, predicate);
  575. }
  576. private static IEnumerable<TSource> SkipWhileYield<TSource>(
  577. IEnumerable<TSource> source,
  578. Func<TSource, int, bool> predicate)
  579. {
  580. using (var e = source.GetEnumerator())
  581. {
  582. for (var i = 0;; i++)
  583. {
  584. if (!e.MoveNext())
  585. yield break;
  586. if (!predicate(e.Current, i))
  587. break;
  588. }
  589. do
  590. {
  591. yield return e.Current;
  592. } while (e.MoveNext());
  593. }
  594. }
  595. /// <summary>
  596. /// Returns the number of elements in a sequence.
  597. /// </summary>
  598. public static int Count<TSource>(
  599. this IEnumerable<TSource> source)
  600. {
  601. CheckNotNull(source, "source");
  602. var collection = source as ICollection;
  603. if (collection != null)
  604. {
  605. return collection.Count;
  606. }
  607. using (var en = source.GetEnumerator())
  608. {
  609. int count = 0;
  610. while (en.MoveNext())
  611. {
  612. ++count;
  613. }
  614. return count;
  615. }
  616. }
  617. /// <summary>
  618. /// Returns a number that represents how many elements in the
  619. /// specified sequence satisfy a condition.
  620. /// </summary>
  621. public static int Count<TSource>(
  622. this IEnumerable<TSource> source,
  623. Func<TSource, bool> predicate)
  624. {
  625. return Count(source.Where(predicate));
  626. }
  627. /// <summary>
  628. /// Returns a <see cref="Int64"/> that represents the total number
  629. /// of elements in a sequence.
  630. /// </summary>
  631. public static long LongCount<TSource>(
  632. this IEnumerable<TSource> source)
  633. {
  634. CheckNotNull(source, "source");
  635. var array = source as Array;
  636. return array != null
  637. ? array.LongLength
  638. : source.Aggregate(0L, (count, item) => count + 1);
  639. }
  640. /// <summary>
  641. /// Returns a <see cref="Int64"/> that represents how many elements
  642. /// in a sequence satisfy a condition.
  643. /// </summary>
  644. public static long LongCount<TSource>(
  645. this IEnumerable<TSource> source,
  646. Func<TSource, bool> predicate)
  647. {
  648. return LongCount(source.Where(predicate));
  649. }
  650. /// <summary>
  651. /// Concatenates two sequences.
  652. /// </summary>
  653. public static IEnumerable<TSource> Concat<TSource>(
  654. this IEnumerable<TSource> first,
  655. IEnumerable<TSource> second)
  656. {
  657. CheckNotNull(first, "first");
  658. CheckNotNull(second, "second");
  659. return ConcatYield(first, second);
  660. }
  661. private static IEnumerable<TSource> ConcatYield<TSource>(
  662. IEnumerable<TSource> first,
  663. IEnumerable<TSource> second)
  664. {
  665. foreach (var item in first)
  666. yield return item;
  667. foreach (var item in second)
  668. yield return item;
  669. }
  670. /// <summary>
  671. /// Creates a <see cref="List{T}"/> from an <see cref="IEnumerable{T}"/>.
  672. /// </summary>
  673. public static List<TSource> ToList<TSource>(
  674. this IEnumerable<TSource> source)
  675. {
  676. CheckNotNull(source, "source");
  677. return new List<TSource>(source);
  678. }
  679. /// <summary>
  680. /// Creates an array from an <see cref="IEnumerable{T}"/>.
  681. /// </summary>
  682. public static TSource[] ToArray<TSource>(
  683. this IEnumerable<TSource> source)
  684. {
  685. IList<TSource> ilist = source as IList<TSource>;
  686. if (ilist != null)
  687. {
  688. TSource[] array = new TSource[ilist.Count];
  689. ilist.CopyTo(array, 0);
  690. return array;
  691. }
  692. return source.ToList().ToArray();
  693. }
  694. /// <summary>
  695. /// Returns distinct elements from a sequence by using the default
  696. /// equality comparer to compare values.
  697. /// </summary>
  698. public static IEnumerable<TSource> Distinct<TSource>(
  699. this IEnumerable<TSource> source)
  700. {
  701. return Distinct(source, /* comparer */ null);
  702. }
  703. /// <summary>
  704. /// Returns distinct elements from a sequence by using a specified
  705. /// <see cref="IEqualityComparer{T}"/> to compare values.
  706. /// </summary>
  707. public static IEnumerable<TSource> Distinct<TSource>(
  708. this IEnumerable<TSource> source,
  709. IEqualityComparer<TSource> comparer)
  710. {
  711. CheckNotNull(source, "source");
  712. return DistinctYield(source, comparer);
  713. }
  714. private static IEnumerable<TSource> DistinctYield<TSource>(
  715. IEnumerable<TSource> source,
  716. IEqualityComparer<TSource> comparer)
  717. {
  718. var set = new Dictionary<TSource, object>(comparer);
  719. var gotNull = false;
  720. foreach (var item in source)
  721. {
  722. if (item == null)
  723. {
  724. if (gotNull)
  725. continue;
  726. gotNull = true;
  727. }
  728. else
  729. {
  730. if (set.ContainsKey(item))
  731. continue;
  732. set.Add(item, null);
  733. }
  734. yield return item;
  735. }
  736. }
  737. /// <summary>
  738. /// Creates a <see cref="Lookup{TKey,TElement}" /> from an
  739. /// <see cref="IEnumerable{T}" /> according to a specified key
  740. /// selector function.
  741. /// </summary>
  742. public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
  743. this IEnumerable<TSource> source,
  744. Func<TSource, TKey> keySelector)
  745. {
  746. return ToLookup(source, keySelector, e => e, /* comparer */ null);
  747. }
  748. /// <summary>
  749. /// Creates a <see cref="Lookup{TKey,TElement}" /> from an
  750. /// <see cref="IEnumerable{T}" /> according to a specified key
  751. /// selector function and a key comparer.
  752. /// </summary>
  753. public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
  754. this IEnumerable<TSource> source,
  755. Func<TSource, TKey> keySelector,
  756. IEqualityComparer<TKey> comparer)
  757. {
  758. return ToLookup(source, keySelector, e => e, comparer);
  759. }
  760. /// <summary>
  761. /// Creates a <see cref="Lookup{TKey,TElement}" /> from an
  762. /// <see cref="IEnumerable{T}" /> according to specified key
  763. /// and element selector functions.
  764. /// </summary>
  765. public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
  766. this IEnumerable<TSource> source,
  767. Func<TSource, TKey> keySelector,
  768. Func<TSource, TElement> elementSelector)
  769. {
  770. return ToLookup(source, keySelector, elementSelector, /* comparer */ null);
  771. }
  772. /// <summary>
  773. /// Creates a <see cref="Lookup{TKey,TElement}" /> from an
  774. /// <see cref="IEnumerable{T}" /> according to a specified key
  775. /// selector function, a comparer and an element selector function.
  776. /// </summary>
  777. public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
  778. this IEnumerable<TSource> source,
  779. Func<TSource, TKey> keySelector,
  780. Func<TSource, TElement> elementSelector,
  781. IEqualityComparer<TKey> comparer)
  782. {
  783. CheckNotNull(source, "source");
  784. CheckNotNull(keySelector, "keySelector");
  785. CheckNotNull(elementSelector, "elementSelector");
  786. var lookup = new Lookup<TKey, TElement>(comparer);
  787. foreach (var item in source)
  788. {
  789. var key = keySelector(item);
  790. var grouping = (Grouping<TKey, TElement>) lookup.Find(key);
  791. if (grouping == null)
  792. {
  793. grouping = new Grouping<TKey, TElement>(key);
  794. lookup.Add(grouping);
  795. }
  796. grouping.Add(elementSelector(item));
  797. }
  798. return lookup;
  799. }
  800. /// <summary>
  801. /// Groups the elements of a sequence according to a specified key
  802. /// selector function.
  803. /// </summary>
  804. public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
  805. this IEnumerable<TSource> source,
  806. Func<TSource, TKey> keySelector)
  807. {
  808. return GroupBy(source, keySelector, /* comparer */ null);
  809. }
  810. /// <summary>
  811. /// Groups the elements of a sequence according to a specified key
  812. /// selector function and compares the keys by using a specified
  813. /// comparer.
  814. /// </summary>
  815. public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
  816. this IEnumerable<TSource> source,
  817. Func<TSource, TKey> keySelector,
  818. IEqualityComparer<TKey> comparer)
  819. {
  820. return GroupBy(source, keySelector, e => e, comparer);
  821. }
  822. /// <summary>
  823. /// Groups the elements of a sequence according to a specified key
  824. /// selector function and projects the elements for each group by
  825. /// using a specified function.
  826. /// </summary>
  827. public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
  828. this IEnumerable<TSource> source,
  829. Func<TSource, TKey> keySelector,
  830. Func<TSource, TElement> elementSelector)
  831. {
  832. return GroupBy(source, keySelector, elementSelector, /* comparer */ null);
  833. }
  834. /// <summary>
  835. /// Groups the elements of a sequence according to a specified key
  836. /// selector function and creates a result value from each group and
  837. /// its key.
  838. /// </summary>
  839. public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
  840. this IEnumerable<TSource> source,
  841. Func<TSource, TKey> keySelector,
  842. Func<TSource, TElement> elementSelector,
  843. IEqualityComparer<TKey> comparer)
  844. {
  845. CheckNotNull(source, "source");
  846. CheckNotNull(keySelector, "keySelector");
  847. CheckNotNull(elementSelector, "elementSelector");
  848. return ToLookup(source, keySelector, elementSelector, comparer);
  849. }
  850. /// <summary>
  851. /// Groups the elements of a sequence according to a key selector
  852. /// function. The keys are compared by using a comparer and each
  853. /// group's elements are projected by using a specified function.
  854. /// </summary>
  855. public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(
  856. this IEnumerable<TSource> source,
  857. Func<TSource, TKey> keySelector,
  858. Func<TKey, IEnumerable<TSource>, TResult> resultSelector)
  859. {
  860. return GroupBy(source, keySelector, resultSelector, /* comparer */ null);
  861. }
  862. /// <summary>
  863. /// Groups the elements of a sequence according to a specified key
  864. /// selector function and creates a result value from each group and
  865. /// its key. The elements of each group are projected by using a
  866. /// specified function.
  867. /// </summary>
  868. public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(
  869. this IEnumerable<TSource> source,
  870. Func<TSource, TKey> keySelector,
  871. Func<TKey, IEnumerable<TSource>, TResult> resultSelector,
  872. IEqualityComparer<TKey> comparer)
  873. {
  874. CheckNotNull(source, "source");
  875. CheckNotNull(keySelector, "keySelector");
  876. CheckNotNull(resultSelector, "resultSelector");
  877. return ToLookup(source, keySelector, comparer).Select(g => resultSelector(g.Key, g));
  878. }
  879. /// <summary>
  880. /// Groups the elements of a sequence according to a specified key
  881. /// selector function and creates a result value from each group and
  882. /// its key. The keys are compared by using a specified comparer.
  883. /// </summary>
  884. public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(
  885. this IEnumerable<TSource> source,
  886. Func<TSource, TKey> keySelector,
  887. Func<TSource, TElement> elementSelector,
  888. Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
  889. {
  890. return GroupBy(source, keySelector, elementSelector, resultSelector, /* comparer */ null);
  891. }
  892. /// <summary>
  893. /// Groups the elements of a sequence according to a specified key
  894. /// selector function and creates a result value from each group and
  895. /// its key. Key values are compared by using a specified comparer,
  896. /// and the elements of each group are projected by using a
  897. /// specified function.
  898. /// </summary>
  899. public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(
  900. this IEnumerable<TSource> source,
  901. Func<TSource, TKey> keySelector,
  902. Func<TSource, TElement> elementSelector,
  903. Func<TKey, IEnumerable<TElement>, TResult> resultSelector,
  904. IEqualityComparer<TKey> comparer)
  905. {
  906. CheckNotNull(source, "source");
  907. CheckNotNull(keySelector, "keySelector");
  908. CheckNotNull(elementSelector, "elementSelector");
  909. CheckNotNull(resultSelector, "resultSelector");
  910. return ToLookup(source, keySelector, elementSelector, comparer)
  911. .Select(g => resultSelector(g.Key, g));
  912. }
  913. /// <summary>
  914. /// Applies an accumulator function over a sequence.
  915. /// </summary>
  916. public static TSource Aggregate<TSource>(
  917. this IEnumerable<TSource> source,
  918. Func<TSource, TSource, TSource> func)
  919. {
  920. CheckNotNull(source, "source");
  921. CheckNotNull(func, "func");
  922. using (var e = source.GetEnumerator())
  923. {
  924. if (!e.MoveNext())
  925. throw new InvalidOperationException();
  926. return e.Renumerable().Skip(1).Aggregate(e.Current, func);
  927. }
  928. }
  929. /// <summary>
  930. /// Applies an accumulator function over a sequence. The specified
  931. /// seed value is used as the initial accumulator value.
  932. /// </summary>
  933. public static TAccumulate Aggregate<TSource, TAccumulate>(
  934. this IEnumerable<TSource> source,
  935. TAccumulate seed,
  936. Func<TAccumulate, TSource, TAccumulate> func)
  937. {
  938. return Aggregate(source, seed, func, r => r);
  939. }
  940. /// <summary>
  941. /// Applies an accumulator function over a sequence. The specified
  942. /// seed value is used as the initial accumulator value, and the
  943. /// specified function is used to select the result value.
  944. /// </summary>
  945. public static TResult Aggregate<TSource, TAccumulate, TResult>(
  946. this IEnumerable<TSource> source,
  947. TAccumulate seed,
  948. Func<TAccumulate, TSource, TAccumulate> func,
  949. Func<TAccumulate, TResult> resultSelector)
  950. {
  951. CheckNotNull(source, "source");
  952. CheckNotNull(func, "func");
  953. CheckNotNull(resultSelector, "resultSelector");
  954. var result = seed;
  955. foreach (var item in source)
  956. result = func(result, item);
  957. return resultSelector(result);
  958. }
  959. /// <summary>
  960. /// Produces the set union of two sequences by using the default
  961. /// equality comparer.
  962. /// </summary>
  963. public static IEnumerable<TSource> Union<TSource>(
  964. this IEnumerable<TSource> first,
  965. IEnumerable<TSource> second)
  966. {
  967. return Union(first, second, /* comparer */ null);
  968. }
  969. /// <summary>
  970. /// Produces the set union of two sequences by using a specified
  971. /// <see cref="IEqualityComparer{T}" />.
  972. /// </summary>
  973. public static IEnumerable<TSource> Union<TSource>(
  974. this IEnumerable<TSource> first,
  975. IEnumerable<TSource> second,
  976. IEqualityComparer<TSource> comparer)
  977. {
  978. return first.Concat(second).Distinct(comparer);
  979. }
  980. /// <summary>
  981. /// Returns the elements of the specified sequence or the type
  982. /// parameter's default value in a singleton collection if the
  983. /// sequence is empty.
  984. /// </summary>
  985. public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
  986. this IEnumerable<TSource> source)
  987. {
  988. return source.DefaultIfEmpty(default(TSource));
  989. }
  990. /// <summary>
  991. /// Returns the elements of the specified sequence or the specified
  992. /// value in a singleton collection if the sequence is empty.
  993. /// </summary>
  994. public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
  995. this IEnumerable<TSource> source,
  996. TSource defaultValue)
  997. {
  998. CheckNotNull(source, "source");
  999. return DefaultIfEmptyYield(source, defaultValue);
  1000. }
  1001. private static IEnumerable<TSource> DefaultIfEmptyYield<TSource>(
  1002. IEnumerable<TSource> source,
  1003. TSource defaultValue)
  1004. {
  1005. using (var e = source.GetEnumerator())
  1006. {
  1007. if (!e.MoveNext())
  1008. yield return defaultValue;
  1009. else
  1010. do
  1011. {
  1012. yield return e.Current;
  1013. } while (e.MoveNext());
  1014. }
  1015. }
  1016. /// <summary>
  1017. /// Determines whether all elements of a sequence satisfy a condition.
  1018. /// </summary>
  1019. public static bool All<TSource>(
  1020. this IEnumerable<TSource> source,
  1021. Func<TSource, bool> predicate)
  1022. {
  1023. CheckNotNull(source, "source");
  1024. CheckNotNull(predicate, "predicate");
  1025. foreach (var item in source)
  1026. if (!predicate(item))
  1027. return false;
  1028. return true;
  1029. }
  1030. /// <summary>
  1031. /// Determines whether a sequence contains any elements.
  1032. /// </summary>
  1033. public static bool Any<TSource>(
  1034. this IEnumerable<TSource> source)
  1035. {
  1036. CheckNotNull(source, "source");
  1037. using (var e = source.GetEnumerator())
  1038. return e.MoveNext();
  1039. }
  1040. /// <summary>
  1041. /// Determines whether any element of a sequence satisfies a
  1042. /// condition.
  1043. /// </summary>
  1044. public static bool Any<TSource>(
  1045. this IEnumerable<TSource> source,
  1046. Func<TSource, bool> predicate)
  1047. {
  1048. foreach (TSource item in source)
  1049. {
  1050. if (predicate(item))
  1051. {
  1052. return true;
  1053. }
  1054. }
  1055. return false;
  1056. }
  1057. /// <summary>
  1058. /// Determines whether a sequence contains a specified element by
  1059. /// using the default equality comparer.
  1060. /// </summary>
  1061. public static bool Contains<TSource>(
  1062. this IEnumerable<TSource> source,
  1063. TSource value)
  1064. {
  1065. return source.Contains(value, /* comparer */ null);
  1066. }
  1067. /// <summary>
  1068. /// Determines whether a sequence contains a specified element by
  1069. /// using a specified <see cref="IEqualityComparer{T}" />.
  1070. /// </summary>
  1071. public static bool Contains<TSource>(
  1072. this IEnumerable<TSource> source,
  1073. TSource value,
  1074. IEqualityComparer<TSource> comparer)
  1075. {
  1076. CheckNotNull(source, "source");
  1077. if (comparer == null)
  1078. {
  1079. var collection = source as ICollection<TSource>;
  1080. if (collection != null)
  1081. return collection.Contains(value);
  1082. }
  1083. comparer = comparer ?? EqualityComparer<TSource>.Default;
  1084. return source.Any(item => comparer.Equals(item, value));
  1085. }
  1086. /// <summary>
  1087. /// Determines whether two sequences are equal by comparing the
  1088. /// elements by using the default equality comparer for their type.
  1089. /// </summary>
  1090. public static bool SequenceEqual<TSource>(
  1091. this IEnumerable<TSource> first,
  1092. IEnumerable<TSource> second)
  1093. {
  1094. return first.SequenceEqual(second, /* comparer */ null);
  1095. }
  1096. /// <summary>
  1097. /// Determines whether two sequences are equal by comparing their
  1098. /// elements by using a specified <see cref="IEqualityComparer{T}" />.
  1099. /// </summary>
  1100. public static bool SequenceEqual<TSource>(
  1101. this IEnumerable<TSource> first,
  1102. IEnumerable<TSource> second,
  1103. IEqualityComparer<TSource> comparer)
  1104. {
  1105. CheckNotNull(first, "first");
  1106. CheckNotNull(second, "second");
  1107. comparer = comparer ?? EqualityComparer<TSource>.Default;
  1108. using (IEnumerator<TSource> lhs = first.GetEnumerator(),
  1109. rhs = second.GetEnumerator())
  1110. {
  1111. do
  1112. {
  1113. if (!lhs.MoveNext())
  1114. return !rhs.MoveNext();
  1115. if (!rhs.MoveNext())
  1116. return false;
  1117. } while (comparer.Equals(lhs.Current, rhs.Current));
  1118. }
  1119. return false;
  1120. }
  1121. /// <summary>
  1122. /// Base implementation for Min/Max operator.
  1123. /// </summary>
  1124. private static TSource MinMaxImpl<TSource>(
  1125. this IEnumerable<TSource> source,
  1126. Func<TSource, TSource, bool> lesser)
  1127. {
  1128. CheckNotNull(source, "source");
  1129. Debug.Assert(lesser != null);
  1130. return source.Aggregate((a, item) => lesser(a, item) ? a : item);
  1131. }
  1132. /// <summary>
  1133. /// Base implementation for Min/Max operator for nullable types.
  1134. /// </summary>
  1135. private static TSource? MinMaxImpl<TSource>(
  1136. this IEnumerable<TSource?> source,
  1137. TSource? seed, Func<TSource?, TSource?, bool> lesser) where TSource : struct
  1138. {
  1139. CheckNotNull(source, "source");
  1140. Debug.Assert(lesser != null);
  1141. return source.Aggregate(seed, (a, item) => lesser(a, item) ? a : item);
  1142. // == MinMaxImpl(Repeat<TSource?>(null, 1).Concat(source), lesser);
  1143. }
  1144. /// <summary>
  1145. /// Returns the minimum value in a generic sequence.
  1146. /// </summary>
  1147. public static TSource Min<TSource>(
  1148. this IEnumerable<TSource> source)
  1149. {
  1150. var comparer = Comparer<TSource>.Default;
  1151. return source.MinMaxImpl((x, y) => comparer.Compare(x, y) < 0);
  1152. }
  1153. /// <summary>
  1154. /// Invokes a transform function on each element of a generic
  1155. /// sequence and returns the minimum resulting value.
  1156. /// </summary>
  1157. public static TResult Min<TSource, TResult>(
  1158. this IEnumerable<TSource> source,
  1159. Func<TSource, TResult> selector)
  1160. {
  1161. return source.Select(selector).Min();
  1162. }
  1163. /// <summary>
  1164. /// Returns the maximum value in a generic sequence.
  1165. /// </summary>
  1166. public static TSource Max<TSource>(
  1167. this IEnumerable<TSource> source)
  1168. {
  1169. var comparer = Comparer<TSource>.Default;
  1170. return source.MinMaxImpl((x, y) => comparer.Compare(x, y) > 0);
  1171. }
  1172. /// <summary>
  1173. /// Invokes a transform function on each element of a generic
  1174. /// sequence and returns the maximum resulting value.
  1175. /// </summary>
  1176. public static TResult Max<TSource, TResult>(
  1177. this IEnumerable<TSource> source,
  1178. Func<TSource, TResult> selector)
  1179. {
  1180. return source.Select(selector).Max();
  1181. }
  1182. /// <summary>
  1183. /// Makes an enumerator seen as enumerable once more.
  1184. /// </summary>
  1185. /// <remarks>
  1186. /// The supplied enumerator must have been started. The first element
  1187. /// returned is the element the enumerator was on when passed in.
  1188. /// DO NOT use this method if the caller must be a generator. It is
  1189. /// mostly safe among aggregate operations.
  1190. /// </remarks>
  1191. private static IEnumerable<T> Renumerable<T>(this IEnumerator<T> e)
  1192. {
  1193. Debug.Assert(e != null);
  1194. do
  1195. {
  1196. yield return e.Current;
  1197. } while (e.MoveNext());
  1198. }
  1199. /// <summary>
  1200. /// Sorts the elements of a sequence in ascending order according to a key.
  1201. /// </summary>
  1202. public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
  1203. this IEnumerable<TSource> source,
  1204. Func<TSource, TKey> keySelector)
  1205. {
  1206. return source.OrderBy(keySelector, /* comparer */ null);
  1207. }
  1208. /// <summary>
  1209. /// Sorts the elements of a sequence in ascending order by using a
  1210. /// specified comparer.
  1211. /// </summary>
  1212. public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
  1213. this IEnumerable<TSource> source,
  1214. Func<TSource, TKey> keySelector,
  1215. IComparer<TKey> comparer)
  1216. {
  1217. CheckNotNull(source, "source");
  1218. CheckNotNull(keySelector, "keySelector");
  1219. return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, /* descending */ false);
  1220. }
  1221. /// <summary>
  1222. /// Sorts the elements of a sequence in descending order according to a key.
  1223. /// </summary>
  1224. public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
  1225. this IEnumerable<TSource> source,
  1226. Func<TSource, TKey> keySelector)
  1227. {
  1228. return source.OrderByDescending(keySelector, /* comparer */ null);
  1229. }
  1230. /// <summary>
  1231. /// Sorts the elements of a sequence in descending order by using a
  1232. /// specified comparer.
  1233. /// </summary>
  1234. public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
  1235. this IEnumerable<TSource> source,
  1236. Func<TSource, TKey> keySelector,
  1237. IComparer<TKey> comparer)
  1238. {
  1239. CheckNotNull(source, "source");
  1240. CheckNotNull(source, "keySelector");
  1241. return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, /* descending */ true);
  1242. }
  1243. /// <summary>
  1244. /// Performs a subsequent ordering of the elements in a sequence in
  1245. /// ascending order according to a key.
  1246. /// </summary>
  1247. public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
  1248. this IOrderedEnumerable<TSource> source,
  1249. Func<TSource, TKey> keySelector)
  1250. {
  1251. return source.ThenBy(keySelector, /* comparer */ null);
  1252. }
  1253. /// <summary>
  1254. /// Performs a subsequent ordering of the elements in a sequence in
  1255. /// ascending order by using a specified comparer.
  1256. /// </summary>
  1257. public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
  1258. this IOrderedEnumerable<TSource> source,
  1259. Func<TSource, TKey> keySelector,
  1260. IComparer<TKey> comparer)
  1261. {
  1262. CheckNotNull(source, "source");
  1263. return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ false);
  1264. }
  1265. /// <summary>
  1266. /// Performs a subsequent ordering of the elements in a sequence in
  1267. /// descending order, according to a key.
  1268. /// </summary>
  1269. public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
  1270. this IOrderedEnumerable<TSource> source,
  1271. Func<TSource, TKey> keySelector)
  1272. {
  1273. return source.ThenByDescending(keySelector, /* comparer */ null);
  1274. }
  1275. /// <summary>
  1276. /// Performs a subsequent ordering of the elements in a sequence in
  1277. /// descending order by using a specified comparer.
  1278. /// </summary>
  1279. public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
  1280. this IOrderedEnumerable<TSource> source,
  1281. Func<TSource, TKey> keySelector,
  1282. IComparer<TKey> comparer)
  1283. {
  1284. CheckNotNull(source, "source");
  1285. return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ true);
  1286. }
  1287. /// <summary>
  1288. /// Base implementation for Intersect and Except operators.
  1289. /// </summary>
  1290. private static IEnumerable<TSource> IntersectExceptImpl<TSource>(
  1291. this IEnumerable<TSource> first,
  1292. IEnumerable<TSource> second,
  1293. IEqualityComparer<TSource> comparer,
  1294. bool flag)
  1295. {
  1296. CheckNotNull(first, "first");
  1297. CheckNotNull(second, "second");
  1298. var keys = new List<TSource>();
  1299. var flags = new Dictionary<TSource, bool>(comparer);
  1300. foreach (var item in first.Where(k => !flags.ContainsKey(k)))
  1301. {
  1302. flags.Add(item, !flag);
  1303. keys.Add(item);
  1304. }
  1305. foreach (var item in second.Where(flags.ContainsKey))
  1306. flags[item] = flag;
  1307. //
  1308. // As per docs, "the marked elements are yielded in the order in
  1309. // which they were collected.
  1310. //
  1311. return keys.Where(item => flags[item]);
  1312. }
  1313. /// <summary>
  1314. /// Produces the set intersection of two sequences by using the
  1315. /// default equality comparer to compare values.
  1316. /// </summary>
  1317. public static IEnumerable<TSource> Intersect<TSource>(
  1318. this IEnumerable<TSource> first,
  1319. IEnumerable<TSource> second)
  1320. {
  1321. return first.Intersect(second, /* comparer */ null);
  1322. }
  1323. /// <summary>
  1324. /// Produces the set intersection of two sequences by using the
  1325. /// specified <see cref="IEqualityComparer{T}" /> to compare values.
  1326. /// </summary>
  1327. public static IEnumerable<TSource> Intersect<TSource>(
  1328. this IEnumerable<TSource> first,
  1329. IEnumerable<TSource> second,
  1330. IEqualityComparer<TSource> comparer)
  1331. {
  1332. return IntersectExceptImpl(first, second, comparer, /* flag */ true);
  1333. }
  1334. /// <summary>
  1335. /// Produces the set difference of two sequences by using the
  1336. /// default equality comparer to compare values.
  1337. /// </summary>
  1338. public static IEnumerable<TSource> Except<TSource>(
  1339. this IEnumerable<TSource> first,
  1340. IEnumerable<TSource> second)
  1341. {
  1342. return first.Except(second, /* comparer */ null);
  1343. }
  1344. /// <summary>
  1345. /// Produces the set difference of two sequences by using the
  1346. /// specified <see cref="IEqualityComparer{T}" /> to compare values.
  1347. /// </summary>
  1348. public static IEnumerable<TSource> Except<TSource>(
  1349. this IEnumerable<TSource> first,
  1350. IEnumerable<TSource> second,
  1351. IEqualityComparer<TSource> comparer)
  1352. {
  1353. return IntersectExceptImpl(first, second, comparer, /* flag */ false);
  1354. }
  1355. /// <summary>
  1356. /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an
  1357. /// <see cref="IEnumerable{T}" /> according to a specified key
  1358. /// selector function.
  1359. /// </summary>
  1360. public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
  1361. this IEnumerable<TSource> source,
  1362. Func<TSource, TKey> keySelector)
  1363. {
  1364. return source.ToDictionary(keySelector, /* comparer */ null);
  1365. }
  1366. /// <summary>
  1367. /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an
  1368. /// <see cref="IEnumerable{T}" /> according to a specified key
  1369. /// selector function and key comparer.
  1370. /// </summary>
  1371. public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
  1372. this IEnumerable<TSource> source,
  1373. Func<TSource, TKey> keySelector,
  1374. IEqualityComparer<TKey> comparer)
  1375. {
  1376. return source.ToDictionary(keySelector, e => e);
  1377. }
  1378. /// <summary>
  1379. /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an
  1380. /// <see cref="IEnumerable{T}" /> according to specified key
  1381. /// selector and element selector functions.
  1382. /// </summary>
  1383. public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
  1384. this IEnumerable<TSource> source,
  1385. Func<TSource, TKey> keySelector,
  1386. Func<TSource, TElement> elementSelector)
  1387. {
  1388. return source.ToDictionary(keySelector, elementSelector, /* comparer */ null);
  1389. }
  1390. /// <summary>
  1391. /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an
  1392. /// <see cref="IEnumerable{T}" /> according to a specified key
  1393. /// selector function, a comparer, and an element selector function.
  1394. /// </summary>
  1395. public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
  1396. this IEnumerable<TSource> source,
  1397. Func<TSource, TKey> keySelector,
  1398. Func<TSource, TElement> elementSelector,
  1399. IEqualityComparer<TKey> comparer)
  1400. {
  1401. CheckNotNull(source, "source");
  1402. CheckNotNull(keySelector, "keySelector");
  1403. CheckNotNull(elementSelector, "elementSelector");
  1404. var dict = new Dictionary<TKey, TElement>(comparer);
  1405. foreach (var item in source)
  1406. {
  1407. //
  1408. // ToDictionary is meant to throw ArgumentNullException if
  1409. // keySelector produces a key that is null and
  1410. // Argument exception if keySelector produces duplicate keys
  1411. // for two elements. Incidentally, the documentation for
  1412. // IDictionary<TKey, TValue>.Add says that the Add method
  1413. // throws the same exceptions under the same circumstances
  1414. // so we don't need to do any additional checking or work
  1415. // here and let the Add implementation do all the heavy
  1416. // lifting.
  1417. //
  1418. dict.Add(keySelector(item), elementSelector(item));
  1419. }
  1420. return dict;
  1421. }
  1422. /// <summary>
  1423. /// Correlates the elements of two sequences based on matching keys.
  1424. /// The default equality comparer is used to compare keys.
  1425. /// </summary>
  1426. public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
  1427. this IEnumerable<TOuter> outer,
  1428. IEnumerable<TInner> inner,
  1429. Func<TOuter, TKey> outerKeySelector,
  1430. Func<TInner, TKey> innerKeySelector,
  1431. Func<TOuter, TInner, TResult> resultSelector)
  1432. {
  1433. return outer.Join(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null);
  1434. }
  1435. /// <summary>
  1436. /// Correlates the elements of two sequences based on matching keys.
  1437. /// The default equality comparer is used to compare keys. A
  1438. /// specified <see cref="IEqualityComparer{T}" /> is used to compare keys.
  1439. /// </summary>
  1440. public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
  1441. this IEnumerable<TOuter> outer,
  1442. IEnumerable<TInner> inner,
  1443. Func<TOuter, TKey> outerKeySelector,
  1444. Func<TInner, TKey> innerKeySelector,
  1445. Func<TOuter, TInner, TResult> resultSelector,
  1446. IEqualityComparer<TKey> comparer)
  1447. {
  1448. CheckNotNull(outer, "outer");
  1449. CheckNotNull(inner, "inner");
  1450. CheckNotNull(outerKeySelector, "outerKeySelector");
  1451. CheckNotNull(innerKeySelector, "innerKeySelector");
  1452. CheckNotNull(resultSelector, "resultSelector");
  1453. var lookup = inner.ToLookup(innerKeySelector, comparer);
  1454. return
  1455. from o in outer
  1456. from i in lookup[outerKeySelector(o)]
  1457. select resultSelector(o, i);
  1458. }
  1459. /// <summary>
  1460. /// Correlates the elements of two sequences based on equality of
  1461. /// keys and groups the results. The default equality comparer is
  1462. /// used to compare keys.
  1463. /// </summary>
  1464. public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
  1465. this IEnumerable<TOuter> outer,
  1466. IEnumerable<TInner> inner,
  1467. Func<TOuter, TKey> outerKeySelector,
  1468. Func<TInner, TKey> innerKeySelector,
  1469. Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
  1470. {
  1471. return outer.GroupJoin(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null);
  1472. }
  1473. /// <summary>
  1474. /// Correlates the elements of two sequences based on equality of
  1475. /// keys and groups the results. The default equality comparer is
  1476. /// used to compare keys. A specified <see cref="IEqualityComparer{T}" />
  1477. /// is used to compare keys.
  1478. /// </summary>
  1479. public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
  1480. this IEnumerable<TOuter> outer,
  1481. IEnumerable<TInner> inner,
  1482. Func<TOuter, TKey> outerKeySelector,
  1483. Func<TInner, TKey> innerKeySelector,
  1484. Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
  1485. IEqualityComparer<TKey> comparer)
  1486. {
  1487. CheckNotNull(outer, "outer");
  1488. CheckNotNull(inner, "inner");
  1489. CheckNotNull(outerKeySelector, "outerKeySelector");
  1490. CheckNotNull(innerKeySelector, "innerKeySelector");
  1491. CheckNotNull(resultSelector, "resultSelector");
  1492. var lookup = inner.ToLookup(innerKeySelector, comparer);
  1493. return outer.Select(o => resultSelector(o, lookup[outerKeySelector(o)]));
  1494. }
  1495. [DebuggerStepThrough]
  1496. private static void CheckNotNull<T>(T value, string name) where T : class
  1497. {
  1498. if (value == null)
  1499. throw new ArgumentNullException(name);
  1500. }
  1501. private static class Sequence<T>
  1502. {
  1503. public static readonly IEnumerable<T> Empty = new T[0];
  1504. }
  1505. private sealed class Grouping<K, V> : List<V>, IGrouping<K, V>
  1506. {
  1507. internal Grouping(K key)
  1508. {
  1509. Key = key;
  1510. }
  1511. public K Key { get; private set; }
  1512. }
  1513. }
  1514. internal partial class Enumerable
  1515. {
  1516. /// <summary>
  1517. /// Computes the sum of a sequence of <see cref="System.Int32" /> values.
  1518. /// </summary>
  1519. public static int Sum(
  1520. this IEnumerable<int> source)
  1521. {
  1522. CheckNotNull(source, "source");
  1523. int sum = 0;
  1524. foreach (var num in source)
  1525. sum = checked(sum + num);
  1526. return sum;
  1527. }
  1528. /// <summary>
  1529. /// Computes the sum of a sequence of <see cref="System.Int32" />
  1530. /// values that are obtained by invoking a transform function on
  1531. /// each element of the input sequence.
  1532. /// </summary>
  1533. public static int Sum<TSource>(
  1534. this IEnumerable<TSource> source,
  1535. Func<TSource, int> selector)
  1536. {
  1537. return source.Select(selector).Sum();
  1538. }
  1539. /// <summary>
  1540. /// Computes the average of a sequence of <see cref="System.Int32" /> values.
  1541. /// </summary>
  1542. public static double Average(
  1543. this IEnumerable<int> source)
  1544. {
  1545. CheckNotNull(source, "source");
  1546. long sum = 0;
  1547. long count = 0;
  1548. foreach (var num in source)
  1549. checked
  1550. {
  1551. sum += (int) num;
  1552. count++;
  1553. }
  1554. if (count == 0)
  1555. throw new InvalidOperationException();
  1556. return (double) sum/count;
  1557. }
  1558. /// <summary>
  1559. /// Computes the average of a sequence of <see cref="System.Int32" /> values
  1560. /// that are obtained by invoking a transform function on each
  1561. /// element of the input sequence.
  1562. /// </summary>
  1563. public static double Average<TSource>(
  1564. this IEnumerable<TSource> source,
  1565. Func<TSource, int> selector)
  1566. {
  1567. return source.Select(selector).Average();
  1568. }
  1569. /// <summary>
  1570. /// Computes the sum of a sequence of nullable <see cref="System.Int32" /> values.
  1571. /// </summary>
  1572. public static int? Sum(
  1573. this IEnumerable<int?> source)
  1574. {
  1575. CheckNotNull(source, "source");
  1576. int sum = 0;
  1577. foreach (var num in source)
  1578. sum = checked(sum + (num ?? 0));
  1579. return sum;
  1580. }
  1581. /// <summary>
  1582. /// Computes the sum of a sequence of nullable <see cref="System.Int32" />
  1583. /// values that are obtained by invoking a transform function on
  1584. /// each element of the input sequence.
  1585. /// </summary>
  1586. public static int? Sum<TSource>(
  1587. this IEnumerable<TSource> source,
  1588. Func<TSource, int?> selector)
  1589. {
  1590. return source.Select(selector).Sum();
  1591. }
  1592. /// <summary>
  1593. /// Computes the average of a sequence of nullable <see cref="System.Int32" /> values.
  1594. /// </summary>
  1595. public static double? Average(
  1596. this IEnumerable<int?> source)
  1597. {
  1598. CheckNotNull(source, "source");
  1599. long sum = 0;
  1600. long count = 0;
  1601. foreach (var num in source.Where(n => n != null))
  1602. checked
  1603. {
  1604. sum += (int) num;
  1605. count++;
  1606. }
  1607. if (count == 0)
  1608. return null;
  1609. return (double?) sum/count;
  1610. }
  1611. /// <summary>
  1612. /// Computes the average of a sequence of nullable <see cref="System.Int32" /> values
  1613. /// that are obtained by invoking a transform function on each
  1614. /// element of the input sequence.
  1615. /// </summary>
  1616. public static double? Average<TSource>(
  1617. this IEnumerable<TSource> source,
  1618. Func<TSource, int?> selector)
  1619. {
  1620. return source.Select(selector).Average();
  1621. }
  1622. /// <summary>
  1623. /// Returns the minimum value in a sequence of nullable
  1624. /// <see cref="System.Int32" /> values.
  1625. /// </summary>
  1626. public static int? Min(
  1627. this IEnumerable<int?> source)
  1628. {
  1629. CheckNotNull(source, "source");
  1630. return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
  1631. }
  1632. /// <summary>
  1633. /// Invokes a transform function on each element of a sequence and
  1634. /// returns the minimum nullable <see cref="System.Int32" /> value.
  1635. /// </summary>
  1636. public static int? Min<TSource>(
  1637. this IEnumerable<TSource> source,
  1638. Func<TSource, int?> selector)
  1639. {
  1640. return source.Select(selector).Min();
  1641. }
  1642. /// <summary>
  1643. /// Returns the maximum value in a sequence of nullable
  1644. /// <see cref="System.Int32" /> values.
  1645. /// </summary>
  1646. public static int? Max(
  1647. this IEnumerable<int?> source)
  1648. {
  1649. CheckNotNull(source, "source");
  1650. return MinMaxImpl(source.Where(x => x != null),
  1651. null, (max, x) => x == null || (max != null && x.Value < max.Value));
  1652. }
  1653. /// <summary>
  1654. /// Invokes a transform function on each element of a sequence and
  1655. /// returns the maximum nullable <see cref="System.Int32" /> value.
  1656. /// </summary>
  1657. public static int? Max<TSource>(
  1658. this IEnumerable<TSource> source,
  1659. Func<TSource, int?> selector)
  1660. {
  1661. return source.Select(selector).Max();
  1662. }
  1663. /// <summary>
  1664. /// Computes the sum of a sequence of <see cref="System.Int64" /> values.
  1665. /// </summary>
  1666. public static long Sum(
  1667. this IEnumerable<long> source)
  1668. {
  1669. CheckNotNull(source, "source");
  1670. long sum = 0;
  1671. foreach (var num in source)
  1672. sum = checked(sum + num);
  1673. return sum;
  1674. }
  1675. /// <summary>
  1676. /// Computes the sum of a sequence of <see cref="System.Int64" />
  1677. /// values that are obtained by invoking a transform function on
  1678. /// each element of the input sequence.
  1679. /// </summary>
  1680. public static long Sum<TSource>(
  1681. this IEnumerable<TSource> source,
  1682. Func<TSource, long> selector)
  1683. {
  1684. return source.Select(selector).Sum();
  1685. }
  1686. /// <summary>
  1687. /// Computes the average of a sequence of <see cref="System.Int64" /> values.
  1688. /// </summary>
  1689. public static double Average(
  1690. this IEnumerable<long> source)
  1691. {
  1692. CheckNotNull(source, "source");
  1693. long sum = 0;
  1694. long count = 0;
  1695. foreach (var num in source)
  1696. checked
  1697. {
  1698. sum += (long) num;
  1699. count++;
  1700. }
  1701. if (count == 0)
  1702. throw new InvalidOperationException();
  1703. return (double) sum/count;
  1704. }
  1705. /// <summary>
  1706. /// Computes the average of a sequence of <see cref="System.Int64" /> values
  1707. /// that are obtained by invoking a transform function on each
  1708. /// element of the input sequence.
  1709. /// </summary>
  1710. public static double Average<TSource>(
  1711. this IEnumerable<TSource> source,
  1712. Func<TSource, long> selector)
  1713. {
  1714. return source.Select(selector).Average();
  1715. }
  1716. /// <summary>
  1717. /// Computes the sum of a sequence of nullable <see cref="System.Int64" /> values.
  1718. /// </summary>
  1719. public static long? Sum(
  1720. this IEnumerable<long?> source)
  1721. {
  1722. CheckNotNull(source, "source");
  1723. long sum = 0;
  1724. foreach (var num in source)
  1725. sum = checked(sum + (num ?? 0));
  1726. return sum;
  1727. }
  1728. /// <summary>
  1729. /// Computes the sum of a sequence of nullable <see cref="System.Int64" />
  1730. /// values that are obtained by invoking a transform function on
  1731. /// each element of the input sequence.
  1732. /// </summary>
  1733. public static long? Sum<TSource>(
  1734. this IEnumerable<TSource> source,
  1735. Func<TSource, long?> selector)
  1736. {
  1737. return source.Select(selector).Sum();
  1738. }
  1739. /// <summary>
  1740. /// Computes the average of a sequence of nullable <see cref="System.Int64" /> values.
  1741. /// </summary>
  1742. public static double? Average(
  1743. this IEnumerable<long?> source)
  1744. {
  1745. CheckNotNull(source, "source");
  1746. long sum = 0;
  1747. long count = 0;
  1748. foreach (var num in source.Where(n => n != null))
  1749. checked
  1750. {
  1751. sum += (long) num;
  1752. count++;
  1753. }
  1754. if (count == 0)
  1755. return null;
  1756. return (double?) sum/count;
  1757. }
  1758. /// <summary>
  1759. /// Computes the average of a sequence of nullable <see cref="System.Int64" /> values
  1760. /// that are obtained by invoking a transform function on each
  1761. /// element of the input sequence.
  1762. /// </summary>
  1763. public static double? Average<TSource>(
  1764. this IEnumerable<TSource> source,
  1765. Func<TSource, long?> selector)
  1766. {
  1767. return source.Select(selector).Average();
  1768. }
  1769. /// <summary>
  1770. /// Returns the minimum value in a sequence of nullable
  1771. /// <see cref="System.Int64" /> values.
  1772. /// </summary>
  1773. public static long? Min(
  1774. this IEnumerable<long?> source)
  1775. {
  1776. CheckNotNull(source, "source");
  1777. return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
  1778. }
  1779. /// <summary>
  1780. /// Invokes a transform function on each element of a sequence and
  1781. /// returns the minimum nullable <see cref="System.Int64" /> value.
  1782. /// </summary>
  1783. public static long? Min<TSource>(
  1784. this IEnumerable<TSource> source,
  1785. Func<TSource, long?> selector)
  1786. {
  1787. return source.Select(selector).Min();
  1788. }
  1789. /// <summary>
  1790. /// Returns the maximum value in a sequence of nullable
  1791. /// <see cref="System.Int64" /> values.
  1792. /// </summary>
  1793. public static long? Max(
  1794. this IEnumerable<long?> source)
  1795. {
  1796. CheckNotNull(source, "source");
  1797. return MinMaxImpl(source.Where(x => x != null),
  1798. null, (max, x) => x == null || (max != null && x.Value < max.Value));
  1799. }
  1800. /// <summary>
  1801. /// Invokes a transform function on each element of a sequence and
  1802. /// returns the maximum nullable <see cref="System.Int64" /> value.
  1803. /// </summary>
  1804. public static long? Max<TSource>(
  1805. this IEnumerable<TSource> source,
  1806. Func<TSource, long?> selector)
  1807. {
  1808. return source.Select(selector).Max();
  1809. }
  1810. /// <summary>
  1811. /// Computes the sum of a sequence of nullable <see cref="System.Single" /> values.
  1812. /// </summary>
  1813. public static float Sum(
  1814. this IEnumerable<float> source)
  1815. {
  1816. CheckNotNull(source, "source");
  1817. float sum = 0;
  1818. foreach (var num in source)
  1819. sum = checked(sum + num);
  1820. return sum;
  1821. }
  1822. /// <summary>
  1823. /// Computes the sum of a sequence of <see cref="System.Single" />
  1824. /// values that are obtained by invoking a transform function on
  1825. /// each element of the input sequence.
  1826. /// </summary>
  1827. public static float Sum<TSource>(
  1828. this IEnumerable<TSource> source,
  1829. Func<TSource, float> selector)
  1830. {
  1831. return source.Select(selector).Sum();
  1832. }
  1833. /// <summary>
  1834. /// Computes the average of a sequence of <see cref="System.Single" /> values.
  1835. /// </summary>
  1836. public static float Average(
  1837. this IEnumerable<float> source)
  1838. {
  1839. CheckNotNull(source, "source");
  1840. float sum = 0;
  1841. long count = 0;
  1842. foreach (var num in source)
  1843. checked
  1844. {
  1845. sum += (float) num;
  1846. count++;
  1847. }
  1848. if (count == 0)
  1849. throw new InvalidOperationException();
  1850. return (float) sum/count;
  1851. }
  1852. /// <summary>
  1853. /// Computes the average of a sequence of <see cref="System.Single" /> values
  1854. /// that are obtained by invoking a transform function on each
  1855. /// element of the input sequence.
  1856. /// </summary>
  1857. public static float Average<TSource>(
  1858. this IEnumerable<TSource> source,
  1859. Func<TSource, float> selector)
  1860. {
  1861. return source.Select(selector).Average();
  1862. }
  1863. /// <summary>
  1864. /// Computes the sum of a sequence of nullable <see cref="System.Single" /> values.
  1865. /// </summary>
  1866. public static float? Sum(
  1867. this IEnumerable<float?> source)
  1868. {
  1869. CheckNotNull(source, "source");
  1870. float sum = 0;
  1871. foreach (var num in source)
  1872. sum = checked(sum + (num ?? 0));
  1873. return sum;
  1874. }
  1875. /// <summary>
  1876. /// Computes the sum of a sequence of nullable <see cref="System.Single" />
  1877. /// values that are obtained by invoking a transform function on
  1878. /// each element of the input sequence.
  1879. /// </summary>
  1880. public static float? Sum<TSource>(
  1881. this IEnumerable<TSource> source,
  1882. Func<TSource, float?> selector)
  1883. {
  1884. return source.Select(selector).Sum();
  1885. }
  1886. /// <summary>
  1887. /// Computes the average of a sequence of nullable <see cref="System.Single" /> values.
  1888. /// </summary>
  1889. public static float? Average(
  1890. this IEnumerable<float?> source)
  1891. {
  1892. CheckNotNull(source, "source");
  1893. float sum = 0;
  1894. long count = 0;
  1895. foreach (var num in source.Where(n => n != null))
  1896. checked
  1897. {
  1898. sum += (float) num;
  1899. count++;
  1900. }
  1901. if (count == 0)
  1902. return null;
  1903. return (float?) sum/count;
  1904. }
  1905. /// <summary>
  1906. /// Computes the average of a sequence of nullable <see cref="System.Single" /> values
  1907. /// that are obtained by invoking a transform function on each
  1908. /// element of the input sequence.
  1909. /// </summary>
  1910. public static float? Average<TSource>(
  1911. this IEnumerable<TSource> source,
  1912. Func<TSource, float?> selector)
  1913. {
  1914. return source.Select(selector).Average();
  1915. }
  1916. /// <summary>
  1917. /// Returns the minimum value in a sequence of nullable
  1918. /// <see cref="System.Single" /> values.
  1919. /// </summary>
  1920. public static float? Min(
  1921. this IEnumerable<float?> source)
  1922. {
  1923. CheckNotNull(source, "source");
  1924. return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
  1925. }
  1926. /// <summary>
  1927. /// Invokes a transform function on each element of a sequence and
  1928. /// returns the minimum nullable <see cref="System.Single" /> value.
  1929. /// </summary>
  1930. public static float? Min<TSource>(
  1931. this IEnumerable<TSource> source,
  1932. Func<TSource, float?> selector)
  1933. {
  1934. return source.Select(selector).Min();
  1935. }
  1936. /// <summary>
  1937. /// Returns the maximum value in a sequence of nullable
  1938. /// <see cref="System.Single" /> values.
  1939. /// </summary>
  1940. public static float? Max(
  1941. this IEnumerable<float?> source)
  1942. {
  1943. CheckNotNull(source, "source");
  1944. return MinMaxImpl(source.Where(x => x != null),
  1945. null, (max, x) => x == null || (max != null && x.Value < max.Value));
  1946. }
  1947. /// <summary>
  1948. /// Invokes a transform function on each element of a sequence and
  1949. /// returns the maximum nullable <see cref="System.Single" /> value.
  1950. /// </summary>
  1951. public static float? Max<TSource>(
  1952. this IEnumerable<TSource> source,
  1953. Func<TSource, float?> selector)
  1954. {
  1955. return source.Select(selector).Max();
  1956. }
  1957. /// <summary>
  1958. /// Computes the sum of a sequence of <see cref="System.Double" /> values.
  1959. /// </summary>
  1960. public static double Sum(
  1961. this IEnumerable<double> source)
  1962. {
  1963. CheckNotNull(source, "source");
  1964. double sum = 0;
  1965. foreach (var num in source)
  1966. sum = checked(sum + num);
  1967. return sum;
  1968. }
  1969. /// <summary>
  1970. /// Computes the sum of a sequence of <see cref="System.Double" />
  1971. /// values that are obtained by invoking a transform function on
  1972. /// each element of the input sequence.
  1973. /// </summary>
  1974. public static double Sum<TSource>(
  1975. this IEnumerable<TSource> source,
  1976. Func<TSource, double> selector)
  1977. {
  1978. return source.Select(selector).Sum();
  1979. }
  1980. /// <summary>
  1981. /// Computes the average of a sequence of <see cref="System.Double" /> values.
  1982. /// </summary>
  1983. public static double Average(
  1984. this IEnumerable<double> source)
  1985. {
  1986. CheckNotNull(source, "source");
  1987. double sum = 0;
  1988. long count = 0;
  1989. foreach (var num in source)
  1990. checked
  1991. {
  1992. sum += (double) num;
  1993. count++;
  1994. }
  1995. if (count == 0)
  1996. throw new InvalidOperationException();
  1997. return (double) sum/count;
  1998. }
  1999. /// <summary>
  2000. /// Computes the average of a sequence of <see cref="System.Double" /> values
  2001. /// that are obtained by invoking a transform function on each
  2002. /// element of the input sequence.
  2003. /// </summary>
  2004. public static double Average<TSource>(
  2005. this IEnumerable<TSource> source,
  2006. Func<TSource, double> selector)
  2007. {
  2008. return source.Select(selector).Average();
  2009. }
  2010. /// <summary>
  2011. /// Computes the sum of a sequence of nullable <see cref="System.Double" /> values.
  2012. /// </summary>
  2013. public static double? Sum(
  2014. this IEnumerable<double?> source)
  2015. {
  2016. CheckNotNull(source, "source");
  2017. double sum = 0;
  2018. foreach (var num in source)
  2019. sum = checked(sum + (num ?? 0));
  2020. return sum;
  2021. }
  2022. /// <summary>
  2023. /// Computes the sum of a sequence of nullable <see cref="System.Double" />
  2024. /// values that are obtained by invoking a transform function on
  2025. /// each element of the input sequence.
  2026. /// </summary>
  2027. public static double? Sum<TSource>(
  2028. this IEnumerable<TSource> source,
  2029. Func<TSource, double?> selector)
  2030. {
  2031. return source.Select(selector).Sum();
  2032. }
  2033. /// <summary>
  2034. /// Computes the average of a sequence of nullable <see cref="System.Double" /> values.
  2035. /// </summary>
  2036. public static double? Average(
  2037. this IEnumerable<double?> source)
  2038. {
  2039. CheckNotNull(source, "source");
  2040. double sum = 0;
  2041. long count = 0;
  2042. foreach (var num in source.Where(n => n != null))
  2043. checked
  2044. {
  2045. sum += (double) num;
  2046. count++;
  2047. }
  2048. if (count == 0)
  2049. return null;
  2050. return (double?) sum/count;
  2051. }
  2052. /// <summary>
  2053. /// Computes the average of a sequence of nullable <see cref="System.Double" /> values
  2054. /// that are obtained by invoking a transform function on each
  2055. /// element of the input sequence.
  2056. /// </summary>
  2057. public static double? Average<TSource>(
  2058. this IEnumerable<TSource> source,
  2059. Func<TSource, double?> selector)
  2060. {
  2061. return source.Select(selector).Average();
  2062. }
  2063. /// <summary>
  2064. /// Returns the minimum value in a sequence of nullable
  2065. /// <see cref="System.Double" /> values.
  2066. /// </summary>
  2067. public static double? Min(
  2068. this IEnumerable<double?> source)
  2069. {
  2070. CheckNotNull(source, "source");
  2071. return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
  2072. }
  2073. /// <summary>
  2074. /// Invokes a transform function on each element of a sequence and
  2075. /// returns the minimum nullable <see cref="System.Double" /> value.
  2076. /// </summary>
  2077. public static double? Min<TSource>(
  2078. this IEnumerable<TSource> source,
  2079. Func<TSource, double?> selector)
  2080. {
  2081. return source.Select(selector).Min();
  2082. }
  2083. /// <summary>
  2084. /// Returns the maximum value in a sequence of nullable
  2085. /// <see cref="System.Double" /> values.
  2086. /// </summary>
  2087. public static double? Max(
  2088. this IEnumerable<double?> source)
  2089. {
  2090. CheckNotNull(source, "source");
  2091. return MinMaxImpl(source.Where(x => x != null),
  2092. null, (max, x) => x == null || (max != null && x.Value < max.Value));
  2093. }
  2094. /// <summary>
  2095. /// Invokes a transform function on each element of a sequence and
  2096. /// returns the maximum nullable <see cref="System.Double" /> value.
  2097. /// </summary>
  2098. public static double? Max<TSource>(
  2099. this IEnumerable<TSource> source,
  2100. Func<TSource, double?> selector)
  2101. {
  2102. return source.Select(selector).Max();
  2103. }
  2104. /// <summary>
  2105. /// Computes the sum of a sequence of <see cref="System.Decimal" /> values.
  2106. /// </summary>
  2107. public static decimal Sum(
  2108. this IEnumerable<decimal> source)
  2109. {
  2110. CheckNotNull(source, "source");
  2111. decimal sum = 0;
  2112. foreach (var num in source)
  2113. sum = checked(sum + num);
  2114. return sum;
  2115. }
  2116. /// <summary>
  2117. /// Computes the sum of a sequence of <see cref="System.Decimal" />
  2118. /// values that are obtained by invoking a transform function on
  2119. /// each element of the input sequence.
  2120. /// </summary>
  2121. public static decimal Sum<TSource>(
  2122. this IEnumerable<TSource> source,
  2123. Func<TSource, decimal> selector)
  2124. {
  2125. CheckNotNull(source, "source");
  2126. CheckNotNull(selector, "selector");
  2127. decimal sum = 0;
  2128. foreach (TSource item in source)
  2129. {
  2130. sum += selector(item);
  2131. }
  2132. return sum;
  2133. }
  2134. /// <summary>
  2135. /// Computes the average of a sequence of <see cref="System.Decimal" /> values.
  2136. /// </summary>
  2137. public static decimal Average(
  2138. this IEnumerable<decimal> source)
  2139. {
  2140. CheckNotNull(source, "source");
  2141. decimal sum = 0;
  2142. long count = 0;
  2143. foreach (var num in source)
  2144. checked
  2145. {
  2146. sum += (decimal) num;
  2147. count++;
  2148. }
  2149. if (count == 0)
  2150. throw new InvalidOperationException();
  2151. return (decimal) sum/count;
  2152. }
  2153. /// <summary>
  2154. /// Computes the average of a sequence of <see cref="System.Decimal" /> values
  2155. /// that are obtained by invoking a transform function on each
  2156. /// element of the input sequence.
  2157. /// </summary>
  2158. public static decimal Average<TSource>(
  2159. this IEnumerable<TSource> source,
  2160. Func<TSource, decimal> selector)
  2161. {
  2162. return source.Select(selector).Average();
  2163. }
  2164. /// <summary>
  2165. /// Computes the sum of a sequence of nullable <see cref="System.Decimal" /> values.
  2166. /// </summary>
  2167. public static decimal? Sum(
  2168. this IEnumerable<decimal?> source)
  2169. {
  2170. CheckNotNull(source, "source");
  2171. decimal sum = 0;
  2172. foreach (var num in source)
  2173. sum = checked(sum + (num ?? 0));
  2174. return sum;
  2175. }
  2176. /// <summary>
  2177. /// Computes the sum of a sequence of nullable <see cref="System.Decimal" />
  2178. /// values that are obtained by invoking a transform function on
  2179. /// each element of the input sequence.
  2180. /// </summary>
  2181. public static decimal? Sum<TSource>(
  2182. this IEnumerable<TSource> source,
  2183. Func<TSource, decimal?> selector)
  2184. {
  2185. return source.Select(selector).Sum();
  2186. }
  2187. /// <summary>
  2188. /// Computes the average of a sequence of nullable <see cref="System.Decimal" /> values.
  2189. /// </summary>
  2190. public static decimal? Average(
  2191. this IEnumerable<decimal?> source)
  2192. {
  2193. CheckNotNull(source, "source");
  2194. decimal sum = 0;
  2195. long count = 0;
  2196. foreach (var num in source.Where(n => n != null))
  2197. checked
  2198. {
  2199. sum += (decimal) num;
  2200. count++;
  2201. }
  2202. if (count == 0)
  2203. return null;
  2204. return (decimal?) sum/count;
  2205. }
  2206. /// <summary>
  2207. /// Computes the average of a sequence of nullable <see cref="System.Decimal" /> values
  2208. /// that are obtained by invoking a transform function on each
  2209. /// element of the input sequence.
  2210. /// </summary>
  2211. public static decimal? Average<TSource>(
  2212. this IEnumerable<TSource> source,
  2213. Func<TSource, decimal?> selector)
  2214. {
  2215. return source.Select(selector).Average();
  2216. }
  2217. /// <summary>
  2218. /// Returns the minimum value in a sequence of nullable
  2219. /// <see cref="System.Decimal" /> values.
  2220. /// </summary>
  2221. public static decimal? Min(
  2222. this IEnumerable<decimal?> source)
  2223. {
  2224. CheckNotNull(source, "source");
  2225. return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
  2226. }
  2227. /// <summary>
  2228. /// Invokes a transform function on each element of a sequence and
  2229. /// returns the minimum nullable <see cref="System.Decimal" /> value.
  2230. /// </summary>
  2231. public static decimal? Min<TSource>(
  2232. this IEnumerable<TSource> source,
  2233. Func<TSource, decimal?> selector)
  2234. {
  2235. return source.Select(selector).Min();
  2236. }
  2237. /// <summary>
  2238. /// Returns the maximum value in a sequence of nullable
  2239. /// <see cref="System.Decimal" /> values.
  2240. /// </summary>
  2241. public static decimal? Max(
  2242. this IEnumerable<decimal?> source)
  2243. {
  2244. CheckNotNull(source, "source");
  2245. return MinMaxImpl(source.Where(x => x != null),
  2246. null, (max, x) => x == null || (max != null && x.Value < max.Value));
  2247. }
  2248. /// <summary>
  2249. /// Invokes a transform function on each element of a sequence and
  2250. /// returns the maximum nullable <see cref="System.Decimal" /> value.
  2251. /// </summary>
  2252. public static decimal? Max<TSource>(
  2253. this IEnumerable<TSource> source,
  2254. Func<TSource, decimal?> selector)
  2255. {
  2256. return source.Select(selector).Max();
  2257. }
  2258. }
  2259. /// <summary>
  2260. /// Represents a collection of objects that have a common key.
  2261. /// </summary>
  2262. internal partial interface IGrouping<TKey, TElement> : IEnumerable<TElement>
  2263. {
  2264. /// <summary>
  2265. /// Gets the key of the <see cref="IGrouping{TKey,TElement}" />.
  2266. /// </summary>
  2267. TKey Key { get; }
  2268. }
  2269. /// <summary>
  2270. /// Defines an indexer, size property, and Boolean search method for
  2271. /// data structures that map keys to <see cref="IEnumerable{T}"/>
  2272. /// sequences of values.
  2273. /// </summary>
  2274. internal partial interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>
  2275. {
  2276. bool Contains(TKey key);
  2277. int Count { get; }
  2278. IEnumerable<TElement> this[TKey key] { get; }
  2279. }
  2280. /// <summary>
  2281. /// Represents a sorted sequence.
  2282. /// </summary>
  2283. internal partial interface IOrderedEnumerable<TElement> : IEnumerable<TElement>
  2284. {
  2285. /// <summary>
  2286. /// Performs a subsequent ordering on the elements of an
  2287. /// <see cref="IOrderedEnumerable{T}"/> according to a key.
  2288. /// </summary>
  2289. IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(
  2290. Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending);
  2291. }
  2292. /// <summary>
  2293. /// Represents a collection of keys each mapped to one or more values.
  2294. /// </summary>
  2295. internal sealed class Lookup<TKey, TElement> : ILookup<TKey, TElement>
  2296. {
  2297. private readonly Dictionary<TKey, IGrouping<TKey, TElement>> _map;
  2298. internal Lookup(IEqualityComparer<TKey> comparer)
  2299. {
  2300. _map = new Dictionary<TKey, IGrouping<TKey, TElement>>(comparer);
  2301. }
  2302. internal void Add(IGrouping<TKey, TElement> item)
  2303. {
  2304. _map.Add(item.Key, item);
  2305. }
  2306. internal IEnumerable<TElement> Find(TKey key)
  2307. {
  2308. IGrouping<TKey, TElement> grouping;
  2309. return _map.TryGetValue(key, out grouping) ? grouping : null;
  2310. }
  2311. /// <summary>
  2312. /// Gets the number of key/value collection pairs in the <see cref="Lookup{TKey,TElement}" />.
  2313. /// </summary>
  2314. public int Count => _map.Count;
  2315. /// <summary>
  2316. /// Gets the collection of values indexed by the specified key.
  2317. /// </summary>
  2318. public IEnumerable<TElement> this[TKey key]
  2319. {
  2320. get
  2321. {
  2322. IGrouping<TKey, TElement> result;
  2323. return _map.TryGetValue(key, out result) ? result : Enumerable.Empty<TElement>();
  2324. }
  2325. }
  2326. /// <summary>
  2327. /// Determines whether a specified key is in the <see cref="Lookup{TKey,TElement}" />.
  2328. /// </summary>
  2329. public bool Contains(TKey key)
  2330. {
  2331. return _map.ContainsKey(key);
  2332. }
  2333. /// <summary>
  2334. /// Applies a transform function to each key and its associated
  2335. /// values and returns the results.
  2336. /// </summary>
  2337. public IEnumerable<TResult> ApplyResultSelector<TResult>(
  2338. Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
  2339. {
  2340. if (resultSelector == null)
  2341. throw new ArgumentNullException("resultSelector");
  2342. foreach (var pair in _map)
  2343. yield return resultSelector(pair.Key, pair.Value);
  2344. }
  2345. /// <summary>
  2346. /// Returns a generic enumerator that iterates through the <see cref="Lookup{TKey,TElement}" />.
  2347. /// </summary>
  2348. public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
  2349. {
  2350. return _map.Values.GetEnumerator();
  2351. }
  2352. IEnumerator IEnumerable.GetEnumerator()
  2353. {
  2354. return GetEnumerator();
  2355. }
  2356. }
  2357. internal sealed class OrderedEnumerable<T, K> : IOrderedEnumerable<T>
  2358. {
  2359. private readonly IEnumerable<T> _source;
  2360. private readonly List<Comparison<T>> _comparisons;
  2361. public OrderedEnumerable(IEnumerable<T> source,
  2362. Func<T, K> keySelector, IComparer<K> comparer, bool descending) :
  2363. this(source, null, keySelector, comparer, descending)
  2364. {
  2365. }
  2366. private OrderedEnumerable(IEnumerable<T> source, List<Comparison<T>> comparisons,
  2367. Func<T, K> keySelector, IComparer<K> comparer, bool descending)
  2368. {
  2369. if (source == null) throw new ArgumentNullException("source");
  2370. if (keySelector == null) throw new ArgumentNullException("keySelector");
  2371. _source = source;
  2372. comparer = comparer ?? Comparer<K>.Default;
  2373. if (comparisons == null)
  2374. comparisons = new List<Comparison<T>>( /* capacity */ 4);
  2375. comparisons.Add((x, y)
  2376. => (descending ? -1 : 1)*comparer.Compare(keySelector(x), keySelector(y)));
  2377. _comparisons = comparisons;
  2378. }
  2379. public IOrderedEnumerable<T> CreateOrderedEnumerable<KK>(
  2380. Func<T, KK> keySelector, IComparer<KK> comparer, bool descending)
  2381. {
  2382. return new OrderedEnumerable<T, KK>(_source, _comparisons, keySelector, comparer, descending);
  2383. }
  2384. public IEnumerator<T> GetEnumerator()
  2385. {
  2386. //
  2387. // We sort using List<T>.Sort, but docs say that it performs an
  2388. // unstable sort. LINQ, on the other hand, says OrderBy performs
  2389. // a stable sort. So convert the source sequence into a sequence
  2390. // of tuples where the second element tags the position of the
  2391. // element from the source sequence (First). The position is
  2392. // then used as a tie breaker when all keys compare equal,
  2393. // thus making the sort stable.
  2394. //
  2395. var list = _source.Select(new Func<T, int, Tuple<T, int>>(TagPosition)).ToList();
  2396. list.Sort((x, y) =>
  2397. {
  2398. //
  2399. // Compare keys from left to right.
  2400. //
  2401. var comparisons = _comparisons;
  2402. for (var i = 0; i < comparisons.Count; i++)
  2403. {
  2404. var result = comparisons[i](x.First, y.First);
  2405. if (result != 0)
  2406. return result;
  2407. }
  2408. //
  2409. // All keys compared equal so now break the tie by their
  2410. // position in the original sequence, making the sort stable.
  2411. //
  2412. return x.Second.CompareTo(y.Second);
  2413. });
  2414. return list.Select(new Func<Tuple<T, int>, T>(GetFirst)).GetEnumerator();
  2415. }
  2416. /// <remarks>
  2417. /// See <a href="http://code.google.com/p/linqbridge/issues/detail?id=11">issue #11</a>
  2418. /// for why this method is needed and cannot be expressed as a
  2419. /// lambda at the call site.
  2420. /// </remarks>
  2421. private static Tuple<T, int> TagPosition(T e, int i)
  2422. {
  2423. return new Tuple<T, int>(e, i);
  2424. }
  2425. /// <remarks>
  2426. /// See <a href="http://code.google.com/p/linqbridge/issues/detail?id=11">issue #11</a>
  2427. /// for why this method is needed and cannot be expressed as a
  2428. /// lambda at the call site.
  2429. /// </remarks>
  2430. private static T GetFirst(Tuple<T, int> pv)
  2431. {
  2432. return pv.First;
  2433. }
  2434. IEnumerator IEnumerable.GetEnumerator()
  2435. {
  2436. return GetEnumerator();
  2437. }
  2438. }
  2439. [Serializable]
  2440. internal readonly struct Tuple<TFirst, TSecond> : IEquatable<Tuple<TFirst, TSecond>>
  2441. {
  2442. public TFirst First { get; }
  2443. public TSecond Second { get; }
  2444. public Tuple(TFirst first, TSecond second)
  2445. : this()
  2446. {
  2447. First = first;
  2448. Second = second;
  2449. }
  2450. public override bool Equals(object obj)
  2451. {
  2452. return obj != null
  2453. && obj is Tuple<TFirst, TSecond>
  2454. && base.Equals((Tuple<TFirst, TSecond>) obj);
  2455. }
  2456. public bool Equals(Tuple<TFirst, TSecond> other)
  2457. {
  2458. return EqualityComparer<TFirst>.Default.Equals(other.First, First)
  2459. && EqualityComparer<TSecond>.Default.Equals(other.Second, Second);
  2460. }
  2461. public override int GetHashCode()
  2462. {
  2463. var num = 0x7a2f0b42;
  2464. num = (-1521134295*num) + EqualityComparer<TFirst>.Default.GetHashCode(First);
  2465. return (-1521134295*num) + EqualityComparer<TSecond>.Default.GetHashCode(Second);
  2466. }
  2467. public override string ToString()
  2468. {
  2469. return string.Format(CultureInfo.InvariantCulture, @"{{ First = {0}, Second = {1} }}", First, Second);
  2470. }
  2471. }
  2472. }
  2473. namespace System.Runtime.CompilerServices
  2474. {
  2475. /// <remarks>
  2476. /// This attribute allows us to define extension methods without
  2477. /// requiring .NET Framework 3.5. For more information, see the section,
  2478. /// <a href="http://msdn.microsoft.com/en-us/magazine/cc163317.aspx#S7">Extension Methods in .NET Framework 2.0 Apps</a>,
  2479. /// of <a href="http://msdn.microsoft.com/en-us/magazine/cc163317.aspx">Basic Instincts: Extension Methods</a>
  2480. /// column in <a href="http://msdn.microsoft.com/msdnmag/">MSDN Magazine</a>,
  2481. /// issue <a href="http://msdn.microsoft.com/en-us/magazine/cc135410.aspx">Nov 2007</a>.
  2482. /// </remarks>
  2483. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
  2484. internal sealed class ExtensionAttribute : Attribute { }
  2485. }
  2486. #endif