Case.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class EnumerableEx
  8. {
  9. /// <summary>
  10. /// Returns a sequence from a dictionary based on the result of evaluating a selector function.
  11. /// </summary>
  12. /// <typeparam name="TValue">Type of the selector value.</typeparam>
  13. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  14. /// <param name="selector">Selector function used to pick a sequence from the given sources.</param>
  15. /// <param name="sources">Dictionary mapping selector values onto resulting sequences.</param>
  16. /// <returns>The source sequence corresponding with the evaluated selector value; otherwise, an empty sequence.</returns>
  17. public static IEnumerable<TResult> Case<TValue, TResult>(Func<TValue> selector, IDictionary<TValue, IEnumerable<TResult>> sources)
  18. {
  19. if (selector == null)
  20. throw new ArgumentNullException(nameof(selector));
  21. if (sources == null)
  22. throw new ArgumentNullException(nameof(sources));
  23. return Case(selector, sources, []);
  24. }
  25. /// <summary>
  26. /// Returns a sequence from a dictionary based on the result of evaluating a selector function, also specifying a
  27. /// default sequence.
  28. /// </summary>
  29. /// <typeparam name="TValue">Type of the selector value.</typeparam>
  30. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  31. /// <param name="selector">Selector function used to pick a sequence from the given sources.</param>
  32. /// <param name="sources">Dictionary mapping selector values onto resulting sequences.</param>
  33. /// <param name="defaultSource">
  34. /// Default sequence to return in case there's no corresponding source for the computed
  35. /// selector value.
  36. /// </param>
  37. /// <returns>The source sequence corresponding with the evaluated selector value; otherwise, the default source.</returns>
  38. public static IEnumerable<TResult> Case<TValue, TResult>(Func<TValue> selector, IDictionary<TValue, IEnumerable<TResult>> sources, IEnumerable<TResult> defaultSource)
  39. {
  40. if (selector == null)
  41. throw new ArgumentNullException(nameof(selector));
  42. if (sources == null)
  43. throw new ArgumentNullException(nameof(sources));
  44. if (defaultSource == null)
  45. throw new ArgumentNullException(nameof(defaultSource));
  46. return Defer(() =>
  47. {
  48. if (!sources.TryGetValue(selector(), out var result))
  49. {
  50. result = defaultSource;
  51. }
  52. return result;
  53. });
  54. }
  55. }
  56. }