Note that there are some explanatory texts on larger screens.

plurals
  1. POElegant way to create a nested Dictionary in C#
    primarykey
    data
    text
    <p><strong>I realized that I didn't give enough information for most people to read my mind and understand all my needs, so I changed this somewhat from the original.</strong></p> <p>Say I've got a list of items of a class like this:</p> <pre><code>public class Thing { int Foo; int Bar; string Baz; } </code></pre> <p>And I want to categorize the Baz string based on the values of Foo, then Bar. There will be at most one Thing for each possible combination of Foo and Bar values, but I'm not guaranteed to have a value for each one. It may help to conceptualize it as cell information for a table: Foo is the row number, Bar is the column number, and Baz is the value to be found there, but there won't necessarily be a value present for every cell.</p> <pre><code>IEnumerable&lt;Thing&gt; things = GetThings(); List&lt;int&gt; foos = GetAllFoos(); List&lt;int&gt; bars = GetAllBars(); Dictionary&lt;int, Dictionary&lt;int, string&gt;&gt; dict = // what do I put here? foreach(int foo in foos) { // I may have code here to do something for each foo... foreach(int bar in bars) { // I may have code here to do something for each bar... if (dict.ContainsKey(foo) &amp;&amp; dict[foo].ContainsKey(bar)) { // I want to have O(1) lookups string baz = dict[foo][bar]; // I may have code here to do something with the baz. } } } </code></pre> <p>What's an easy, elegant way to generate the nested dictionary? I've been using C# long enough that I'm getting used to finding simple, one-line solutions for all of the common stuff like this, but this one has me stumped.</p>
    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.
 

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