Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>EDIT: Complications with type-inference.</p> <p>Here's a way, the idea is to constrain the dictionary-values' type to be an<code>IEnumerable</code>of <em>something</em>.</p> <p>Unfortunately, type-inference doesn't seem to work with this signature (tested with C# 3), so you will have to specify the generic arguments explicitly.</p> <pre><code>public static IEnumerable&lt;TUnderlyingValue&gt; GetValueOrEmpty&lt;TKey, TUnderlyingValue, TValue&gt; (this IDictionary&lt;TKey, TValue&gt; source, TKey key) where TValue : IEnumerable&lt;TUnderlyingValue&gt; { if(source == null) throw new ArgumentNullException("source"); TValue retVal; return source.TryGetValue(key, out retVal) ? retVal : Enumerable.Empty&lt;TUnderlyingValue&gt;; } </code></pre> <p><strong>Usage</strong>:</p> <pre><code>var dict = new Dictionary&lt;string, int[]&gt; { { "foo", new[] { 6, 7, 8 } } { "bar", new[] { 1 } } }; var fooOrEmpty = dict.GetValueOrEmpty&lt;string, int, int[]&gt;("foo"); // { 6, 7, 8 } var barOrEmpty = dict.GetValueOrEmpty&lt;string, int, int[]&gt;("bar"); // { 1 } var bazOrEmpty = dict.GetValueOrEmpty&lt;string, int, int[]&gt;("baz"); // { } </code></pre> <p>Alternatively, we could use just 2 generic parameters without any constraints, but this will make the dictionary type less flexible. In this case, the compiler will infer the generic arguments just fine.</p> <pre><code>public static TUnderlyingValue[] GetValueOrEmpty&lt;TKey, TUnderlyingValue&gt; (this IDictionary&lt;TKey, TUnderlyingValue[]&gt; source, TKey key) { if(source == null) throw new ArgumentNullException("source"); TUnderlyingValue[] retVal; return source.TryGetValue(key, out retVal) ? retVal : new TUnderlyingValue[0]; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload