OrderedDictionary.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. /******************************************************************************
  30. * Thanks to Travis Parks
  31. * https://github.com/jehugaleahsa/truncon.collections.OrderedDictionary
  32. *****************************************************************************/
  33. using System;
  34. using System.Collections;
  35. using System.Collections.Generic;
  36. using System.ComponentModel;
  37. using System.Diagnostics;
  38. using System.Linq;
  39. namespace Spine.Collections
  40. {
  41. /// <summary>
  42. /// Represents a dictionary that tracks the order that items were added.
  43. /// </summary>
  44. /// <typeparam name="TKey">The type of the dictionary keys.</typeparam>
  45. /// <typeparam name="TValue">The type of the dictionary values.</typeparam>
  46. /// <remarks>
  47. /// This dictionary makes it possible to get the index of a key and a key based on an index.
  48. /// It can be costly to find the index of a key because it must be searched for linearly.
  49. /// It can be costly to insert a key/value pair because other key's indexes must be adjusted.
  50. /// It can be costly to remove a key/value pair because other keys' indexes must be adjusted.
  51. /// </remarks>
  52. [DebuggerDisplay("Count = {Count}")]
  53. [DebuggerTypeProxy(typeof(OrderedDictionaryDebugView<,>))]
  54. public sealed class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IList<KeyValuePair<TKey, TValue>>
  55. {
  56. private readonly Dictionary<TKey, int> dictionary;
  57. private readonly List<TKey> keys;
  58. private readonly List<TValue> values;
  59. private int version;
  60. private const string CollectionModifiedMessage = "Collection was modified; enumeration operation may not execute.";
  61. private const string EditReadOnlyListMessage = "An attempt was made to edit a read-only list.";
  62. private const string IndexOutOfRangeMessage = "The index is negative or outside the bounds of the collection.";
  63. /// <summary>
  64. /// Initializes a new instance of an OrderedDictionary.
  65. /// </summary>
  66. public OrderedDictionary ()
  67. : this(0, null) {
  68. }
  69. /// <summary>
  70. /// Initializes a new instance of an OrderedDictionary.
  71. /// </summary>
  72. /// <param name="capacity">The initial capacity of the dictionary.</param>
  73. /// <exception cref="System.ArgumentOutOfRangeException">The capacity is less than zero.</exception>
  74. public OrderedDictionary (int capacity)
  75. : this(capacity, null) {
  76. }
  77. /// <summary>
  78. /// Initializes a new instance of an OrderedDictionary.
  79. /// </summary>
  80. /// <param name="comparer">The equality comparer to use to compare keys.</param>
  81. public OrderedDictionary (IEqualityComparer<TKey> comparer)
  82. : this(0, comparer) {
  83. }
  84. /// <summary>
  85. /// Initializes a new instance of an OrderedDictionary.
  86. /// </summary>
  87. /// <param name="capacity">The initial capacity of the dictionary.</param>
  88. /// <param name="comparer">The equality comparer to use to compare keys.</param>
  89. public OrderedDictionary (int capacity, IEqualityComparer<TKey> comparer) {
  90. dictionary = new Dictionary<TKey, int>(capacity, comparer ?? EqualityComparer<TKey>.Default);
  91. keys = new List<TKey>(capacity);
  92. values = new List<TValue>(capacity);
  93. }
  94. /// <summary>
  95. /// Gets the equality comparer used to compare keys.
  96. /// </summary>
  97. public IEqualityComparer<TKey> Comparer {
  98. get {
  99. return dictionary.Comparer;
  100. }
  101. }
  102. /// <summary>
  103. /// Adds the given key/value pair to the dictionary.
  104. /// </summary>
  105. /// <param name="key">The key to add to the dictionary.</param>
  106. /// <param name="value">The value to associated with the key.</param>
  107. /// <exception cref="System.ArgumentException">The given key already exists in the dictionary.</exception>
  108. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  109. public void Add (TKey key, TValue value) {
  110. dictionary.Add(key, values.Count);
  111. keys.Add(key);
  112. values.Add(value);
  113. ++version;
  114. }
  115. /// <summary>
  116. /// Inserts the given key/value pair at the specified index.
  117. /// </summary>
  118. /// <param name="index">The index to insert the key/value pair.</param>
  119. /// <param name="key">The key to insert.</param>
  120. /// <param name="value">The value to insert.</param>
  121. /// <exception cref="System.ArgumentException">The given key already exists in the dictionary.</exception>
  122. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  123. /// <exception cref="System.ArgumentOutOfRangeException">The index is negative -or- larger than the size of the dictionary.</exception>
  124. public void Insert (int index, TKey key, TValue value) {
  125. if (index < 0 || index > values.Count) {
  126. throw new ArgumentOutOfRangeException("index", index, IndexOutOfRangeMessage);
  127. }
  128. dictionary.Add(key, index);
  129. for (int keyIndex = index; keyIndex != keys.Count; ++keyIndex) {
  130. var otherKey = keys[keyIndex];
  131. dictionary[otherKey] += 1;
  132. }
  133. keys.Insert(index, key);
  134. values.Insert(index, value);
  135. ++version;
  136. }
  137. /// <summary>
  138. /// Determines whether the given key exists in the dictionary.
  139. /// </summary>
  140. /// <param name="key">The key to look for.</param>
  141. /// <returns>True if the key exists in the dictionary; otherwise, false.</returns>
  142. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  143. public bool ContainsKey (TKey key) {
  144. return dictionary.ContainsKey(key);
  145. }
  146. /// <summary>
  147. /// Gets the key at the given index.
  148. /// </summary>
  149. /// <param name="index">The index of the key to get.</param>
  150. /// <returns>The key at the given index.</returns>
  151. /// <exception cref="System.ArgumentOutOfRangeException">The index is negative -or- larger than the number of keys.</exception>
  152. public TKey GetKey (int index) {
  153. return keys[index];
  154. }
  155. /// <summary>
  156. /// Gets the index of the given key.
  157. /// </summary>
  158. /// <param name="key">The key to get the index of.</param>
  159. /// <returns>The index of the key in the dictionary -or- -1 if the key is not found.</returns>
  160. /// <remarks>The operation runs in O(n).</remarks>
  161. public int IndexOf (TKey key) {
  162. int index;
  163. if (dictionary.TryGetValue(key, out index)) {
  164. return index;
  165. }
  166. return -1;
  167. }
  168. /// <summary>
  169. /// Gets the keys in the dictionary in the order they were added.
  170. /// </summary>
  171. public KeyCollection Keys {
  172. get {
  173. return new KeyCollection(this.dictionary);
  174. }
  175. }
  176. /// <summary>
  177. /// Removes the key/value pair with the given key from the dictionary.
  178. /// </summary>
  179. /// <param name="key">The key of the pair to remove.</param>
  180. /// <returns>True if the key was found and the pair removed; otherwise, false.</returns>
  181. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  182. public bool Remove (TKey key) {
  183. int index;
  184. if (dictionary.TryGetValue(key, out index)) {
  185. RemoveAt(index);
  186. return true;
  187. }
  188. return false;
  189. }
  190. /// <summary>
  191. /// Removes the key/value pair at the given index.
  192. /// </summary>
  193. /// <param name="index">The index of the key/value pair to remove.</param>
  194. /// <exception cref="System.ArgumentOutOfRangeException">The index is negative -or- larger than the size of the dictionary.</exception>
  195. public void RemoveAt (int index) {
  196. var key = keys[index];
  197. for (int keyIndex = index + 1; keyIndex < keys.Count; ++keyIndex) {
  198. var otherKey = keys[keyIndex];
  199. dictionary[otherKey] -= 1;
  200. }
  201. dictionary.Remove(key);
  202. keys.RemoveAt(index);
  203. values.RemoveAt(index);
  204. ++version;
  205. }
  206. /// <summary>
  207. /// Tries to get the value associated with the given key. If the key is not found,
  208. /// default(TValue) value is stored in the value.
  209. /// </summary>
  210. /// <param name="key">The key to get the value for.</param>
  211. /// <param name="value">The value used to hold the results.</param>
  212. /// <returns>True if the key was found; otherwise, false.</returns>
  213. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  214. public bool TryGetValue (TKey key, out TValue value) {
  215. int index;
  216. if (dictionary.TryGetValue(key, out index)) {
  217. value = values[index];
  218. return true;
  219. }
  220. value = default(TValue);
  221. return false;
  222. }
  223. /// <summary>
  224. /// Gets the values in the dictionary.
  225. /// </summary>
  226. public ValueCollection Values {
  227. get {
  228. return new ValueCollection(values);
  229. }
  230. }
  231. /// <summary>
  232. /// Gets or sets the value at the given index.
  233. /// </summary>
  234. /// <param name="index">The index of the value to get.</param>
  235. /// <returns>The value at the given index.</returns>
  236. /// <exception cref="System.ArgumentOutOfRangeException">The index is negative -or- beyond the length of the dictionary.</exception>
  237. public TValue this[int index] {
  238. get {
  239. return values[index];
  240. }
  241. set {
  242. values[index] = value;
  243. }
  244. }
  245. /// <summary>
  246. /// Gets or sets the value associated with the given key.
  247. /// </summary>
  248. /// <param name="key">The key to get the associated value by or to associate with the value.</param>
  249. /// <returns>The value associated with the given key.</returns>
  250. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  251. /// <exception cref="System.Collections.Generic.KeyNotFoundException">The key is not in the dictionary.</exception>
  252. public TValue this[TKey key] {
  253. get {
  254. return values[dictionary[key]];
  255. }
  256. set {
  257. int index;
  258. if (dictionary.TryGetValue(key, out index)) {
  259. keys[index] = key;
  260. values[index] = value;
  261. }
  262. else {
  263. Add(key, value);
  264. }
  265. }
  266. }
  267. /// <summary>
  268. /// Removes all key/value pairs from the dictionary.
  269. /// </summary>
  270. public void Clear () {
  271. dictionary.Clear();
  272. keys.Clear();
  273. values.Clear();
  274. ++version;
  275. }
  276. /// <summary>
  277. /// Gets the number of key/value pairs in the dictionary.
  278. /// </summary>
  279. public int Count {
  280. get {
  281. return dictionary.Count;
  282. }
  283. }
  284. /// <summary>
  285. /// Gets the key/value pairs in the dictionary in the order they were added.
  286. /// </summary>
  287. /// <returns>An enumerator over the key/value pairs in the dictionary.</returns>
  288. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator () {
  289. int startVersion = version;
  290. for (int index = 0; index != keys.Count; ++index) {
  291. var key = keys[index];
  292. var value = values[index];
  293. yield return new KeyValuePair<TKey, TValue>(key, value);
  294. if (version != startVersion) {
  295. throw new InvalidOperationException(CollectionModifiedMessage);
  296. }
  297. }
  298. }
  299. int IList<KeyValuePair<TKey, TValue>>.IndexOf (KeyValuePair<TKey, TValue> item) {
  300. int index;
  301. if (dictionary.TryGetValue(item.Key, out index) && Equals(values[index], item.Value)) {
  302. return index;
  303. }
  304. return -1;
  305. }
  306. void IList<KeyValuePair<TKey, TValue>>.Insert (int index, KeyValuePair<TKey, TValue> item) {
  307. Insert(index, item.Key, item.Value);
  308. }
  309. KeyValuePair<TKey, TValue> IList<KeyValuePair<TKey, TValue>>.this[int index] {
  310. get {
  311. TKey key = keys[index];
  312. TValue value = values[index];
  313. return new KeyValuePair<TKey, TValue>(key, value);
  314. }
  315. set {
  316. TKey key = keys[index];
  317. if (dictionary.Comparer.Equals(key, value.Key)) {
  318. dictionary[value.Key] = index;
  319. }
  320. else {
  321. dictionary.Add(value.Key, index); // will throw if key already exists
  322. dictionary.Remove(key);
  323. }
  324. keys[index] = value.Key;
  325. values[index] = value.Value;
  326. }
  327. }
  328. ICollection<TKey> IDictionary<TKey, TValue>.Keys {
  329. get {
  330. return Keys;
  331. }
  332. }
  333. ICollection<TValue> IDictionary<TKey, TValue>.Values {
  334. get {
  335. return Values;
  336. }
  337. }
  338. void ICollection<KeyValuePair<TKey, TValue>>.Add (KeyValuePair<TKey, TValue> item) {
  339. Add(item.Key, item.Value);
  340. }
  341. bool ICollection<KeyValuePair<TKey, TValue>>.Contains (KeyValuePair<TKey, TValue> item) {
  342. int index;
  343. if (dictionary.TryGetValue(item.Key, out index) && Equals(values[index], item.Value)) {
  344. return true;
  345. }
  346. return false;
  347. }
  348. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
  349. if (array == null) {
  350. throw new ArgumentNullException("array");
  351. }
  352. if (arrayIndex < 0) {
  353. throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, IndexOutOfRangeMessage);
  354. }
  355. for (int index = 0; index != keys.Count && arrayIndex < array.Length; ++index, ++arrayIndex) {
  356. var key = keys[index];
  357. var value = values[index];
  358. array[arrayIndex] = new KeyValuePair<TKey, TValue>(key, value);
  359. }
  360. }
  361. bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
  362. get {
  363. return false;
  364. }
  365. }
  366. bool ICollection<KeyValuePair<TKey, TValue>>.Remove (KeyValuePair<TKey, TValue> item) {
  367. ICollection<KeyValuePair<TKey, TValue>> self = this;
  368. if (self.Contains(item)) {
  369. return Remove(item.Key);
  370. }
  371. return false;
  372. }
  373. IEnumerator IEnumerable.GetEnumerator () {
  374. return GetEnumerator();
  375. }
  376. /// <summary>
  377. /// Wraps the keys in an OrderDictionary.
  378. /// </summary>
  379. public sealed class KeyCollection : ICollection<TKey>
  380. {
  381. private readonly Dictionary<TKey, int> dictionary;
  382. /// <summary>
  383. /// Initializes a new instance of a KeyCollection.
  384. /// </summary>
  385. /// <param name="dictionary">The OrderedDictionary whose keys to wrap.</param>
  386. /// <exception cref="System.ArgumentNullException">The dictionary is null.</exception>
  387. internal KeyCollection (Dictionary<TKey, int> dictionary) {
  388. this.dictionary = dictionary;
  389. }
  390. /// <summary>
  391. /// Copies the keys from the OrderedDictionary to the given array, starting at the given index.
  392. /// </summary>
  393. /// <param name="array">The array to copy the keys to.</param>
  394. /// <param name="arrayIndex">The index into the array to start copying the keys.</param>
  395. /// <exception cref="System.ArgumentNullException">The array is null.</exception>
  396. /// <exception cref="System.ArgumentOutOfRangeException">The arrayIndex is negative.</exception>
  397. /// <exception cref="System.ArgumentException">The array, starting at the given index, is not large enough to contain all the keys.</exception>
  398. public void CopyTo (TKey[] array, int arrayIndex) {
  399. dictionary.Keys.CopyTo(array, arrayIndex);
  400. }
  401. /// <summary>
  402. /// Gets the number of keys in the OrderedDictionary.
  403. /// </summary>
  404. public int Count {
  405. get {
  406. return dictionary.Count;
  407. }
  408. }
  409. /// <summary>
  410. /// Gets an enumerator over the keys in the OrderedDictionary.
  411. /// </summary>
  412. /// <returns>The enumerator.</returns>
  413. public IEnumerator<TKey> GetEnumerator () {
  414. return dictionary.Keys.GetEnumerator();
  415. }
  416. [EditorBrowsable(EditorBrowsableState.Never)]
  417. bool ICollection<TKey>.Contains (TKey item) {
  418. return dictionary.ContainsKey(item);
  419. }
  420. [EditorBrowsable(EditorBrowsableState.Never)]
  421. void ICollection<TKey>.Add (TKey item) {
  422. throw new NotSupportedException(EditReadOnlyListMessage);
  423. }
  424. [EditorBrowsable(EditorBrowsableState.Never)]
  425. void ICollection<TKey>.Clear () {
  426. throw new NotSupportedException(EditReadOnlyListMessage);
  427. }
  428. [EditorBrowsable(EditorBrowsableState.Never)]
  429. bool ICollection<TKey>.IsReadOnly {
  430. get {
  431. return true;
  432. }
  433. }
  434. [EditorBrowsable(EditorBrowsableState.Never)]
  435. bool ICollection<TKey>.Remove (TKey item) {
  436. throw new NotSupportedException(EditReadOnlyListMessage);
  437. }
  438. IEnumerator IEnumerable.GetEnumerator () {
  439. return GetEnumerator();
  440. }
  441. }
  442. /// <summary>
  443. /// Wraps the keys in an OrderDictionary.
  444. /// </summary>
  445. public sealed class ValueCollection : ICollection<TValue>
  446. {
  447. private readonly List<TValue> values;
  448. /// <summary>
  449. /// Initializes a new instance of a ValueCollection.
  450. /// </summary>
  451. /// <param name="values">The OrderedDictionary whose keys to wrap.</param>
  452. /// <exception cref="System.ArgumentNullException">The dictionary is null.</exception>
  453. internal ValueCollection (List<TValue> values) {
  454. this.values = values;
  455. }
  456. /// <summary>
  457. /// Copies the values from the OrderedDictionary to the given array, starting at the given index.
  458. /// </summary>
  459. /// <param name="array">The array to copy the values to.</param>
  460. /// <param name="arrayIndex">The index into the array to start copying the values.</param>
  461. /// <exception cref="System.ArgumentNullException">The array is null.</exception>
  462. /// <exception cref="System.ArgumentOutOfRangeException">The arrayIndex is negative.</exception>
  463. /// <exception cref="System.ArgumentException">The array, starting at the given index, is not large enough to contain all the values.</exception>
  464. public void CopyTo (TValue[] array, int arrayIndex) {
  465. values.CopyTo(array, arrayIndex);
  466. }
  467. /// <summary>
  468. /// Gets the number of values in the OrderedDictionary.
  469. /// </summary>
  470. public int Count {
  471. get {
  472. return values.Count;
  473. }
  474. }
  475. /// <summary>
  476. /// Gets an enumerator over the values in the OrderedDictionary.
  477. /// </summary>
  478. /// <returns>The enumerator.</returns>
  479. public IEnumerator<TValue> GetEnumerator () {
  480. return values.GetEnumerator();
  481. }
  482. [EditorBrowsable(EditorBrowsableState.Never)]
  483. bool ICollection<TValue>.Contains (TValue item) {
  484. return values.Contains(item);
  485. }
  486. [EditorBrowsable(EditorBrowsableState.Never)]
  487. void ICollection<TValue>.Add (TValue item) {
  488. throw new NotSupportedException(EditReadOnlyListMessage);
  489. }
  490. [EditorBrowsable(EditorBrowsableState.Never)]
  491. void ICollection<TValue>.Clear () {
  492. throw new NotSupportedException(EditReadOnlyListMessage);
  493. }
  494. [EditorBrowsable(EditorBrowsableState.Never)]
  495. bool ICollection<TValue>.IsReadOnly {
  496. get {
  497. return true;
  498. }
  499. }
  500. [EditorBrowsable(EditorBrowsableState.Never)]
  501. bool ICollection<TValue>.Remove (TValue item) {
  502. throw new NotSupportedException(EditReadOnlyListMessage);
  503. }
  504. IEnumerator IEnumerable.GetEnumerator () {
  505. return GetEnumerator();
  506. }
  507. }
  508. }
  509. internal class OrderedDictionaryDebugView<TKey, TValue>
  510. {
  511. private readonly OrderedDictionary<TKey, TValue> dictionary;
  512. public OrderedDictionaryDebugView (OrderedDictionary<TKey, TValue> dictionary) {
  513. this.dictionary = dictionary;
  514. }
  515. [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
  516. public KeyValuePair<TKey, TValue>[] Items {
  517. get {
  518. return dictionary.ToArray();
  519. }
  520. }
  521. }
  522. /// <summary>
  523. /// Provides extensions methods for constructing instances of <see cref="OrderedDictionary{TKey, TValue}"/>.
  524. /// </summary>
  525. public static class CollectionExtensions
  526. {
  527. #region ToOrderedDictionary
  528. /// <summary>
  529. /// Creates a new OrderedDictionary from the given collection, using the key selector to extract the key.
  530. /// </summary>
  531. /// <typeparam name="TSource">The type of the items in the collection.</typeparam>
  532. /// <typeparam name="TKey">The type of the key.</typeparam>
  533. /// <param name="source">The items to created the OrderedDictionary from.</param>
  534. /// <param name="keySelector">A delegate that can extract a key from an item in the collection.</param>
  535. /// <returns>An OrderedDictionary mapping the extracted keys to their values.</returns>
  536. public static OrderedDictionary<TKey, TSource> ToOrderedDictionary<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) {
  537. return ToOrderedDictionary(source, keySelector, null);
  538. }
  539. /// <summary>
  540. /// Creates a new OrderedDictionary from the given collection, using the key selector to extract the key.
  541. /// The key comparer is passed to the OrderedDictionary for comparing the extracted keys.
  542. /// </summary>
  543. /// <typeparam name="TSource">The type of the items in the collection.</typeparam>
  544. /// <typeparam name="TKey">The type of the key.</typeparam>
  545. /// <param name="source">The items to created the OrderedDictionary from.</param>
  546. /// <param name="keySelector">A delegate that can extract a key from an item in the collection.</param>
  547. /// <param name="comparer">The key equality comparer to use to compare keys in the dictionary.</param>
  548. /// <returns>An OrderedDictionary mapping the extracted keys to their values.</returns>
  549. public static OrderedDictionary<TKey, TSource> ToOrderedDictionary<TSource, TKey> (
  550. this IEnumerable<TSource> source,
  551. Func<TSource, TKey> keySelector,
  552. IEqualityComparer<TKey> comparer) {
  553. if (source == null) {
  554. throw new ArgumentNullException("source");
  555. }
  556. if (keySelector == null) {
  557. throw new ArgumentNullException("keySelector");
  558. }
  559. var dictionary = new OrderedDictionary<TKey, TSource>(comparer);
  560. foreach (TSource item in source) {
  561. TKey key = keySelector(item);
  562. dictionary.Add(key, item);
  563. }
  564. return dictionary;
  565. }
  566. #endregion
  567. }
  568. }