Creating a dictionary of strings and list of strings I have a List of objects, List&lt;myObject&gt; objectList, and each object contains a List of strings like so:

myObject: StringList( "A_1", "B_1", "C_1", "D_1", "E_1", "F_1" )  
myObject: StringList( "A_2", "B_2", "C_1", "D_2", "E_2", "F_1" )  
myObject: StringList( "A_2", "B_3", "C_1", "D_3", "E_2", "F_1" )  


I'm trying to merge the lists into a dictionary of: Dictionary&lt;string, List&lt;string&gt;&gt;, where the final results will look like so:

Dictionary: { [A:1,2]  [B:1,2,3]  [C:1]  [D:1,2,3]  [E:1,2]  [F:1] }


Here is what I have done, and it does work:

Dictionary&lt;string, List&lt;string&gt;&gt; dict = new Dictionary&lt;string, List&lt;string&gt;&gt;();

foreach (myObject result in objectList)
{
    foreach (var item in result.StringList)
    {
        string Key = item.Split('_')[0];
        string Value = item.Split('_')[1];

        List&lt;string&gt; sValue = new List&lt;string&gt;();
        bool exists = dict.TryGetValue(Key, out sValue);

        if (exists &amp;&amp; !sValue.Contains(Value))
        {
            sValue.Add(Value);
            dict[Key] = sValue;
        }
        else if (!exists)
        {
            sValue = sValue ?? new List&lt;string&gt;();
            sValue.Add(Value);
            dict.Add(Key, sValue);
        }
    }
}


Is there a better way to do this, where I don't have to use two foreach loops? Is there a way to do it without using any foreach loops?

I have tried using lambda but this is as far as I got:

Dictionary&lt;string, List&lt;string&gt;&gt; dict = new Dictionary&lt;string, List&lt;string&gt;&gt;();

foreach (myObject result in objectList)
{
    dict = result.StringList.Select(x =&gt; x.Split('_'))
                            .GroupBy(x =&gt; x[0])
                            .ToDictionary(x =&gt; x.Key, x =&gt; x.Select(g =&gt; g[1]).ToList());
}


The problem is that the expression keeps overwriting any existing entries in the dictionary each time I iterate through the loop.

Is there a way to keep the existing entries, groupby the Key and add to the existing list of values but don't duplicate any values?

I think the answer lies in this part of the expression:

x =&gt; x.Select(g =&gt; g[1]).ToList()


but I'm not 100% sure.
Just get rid of the outer foreach as well:

dict = objectList.SelectMany(x =&gt; x.StringList)
       .Select(x =&gt; x.Split('_'))
       .GroupBy(x =&gt; x[0])
       .ToDictionary(x =&gt; x.Key, x =&gt; x.Select(g =&gt; g[1]).Distinct().ToList());


SelectMany retrieves all the StringLists and flattens them into one single list:

"A_1", "B_1", ..., "F_1", "A_2", "B_2", ...