Search code examples
c#.netlinqlistlinq-group

LINQ Dictionary Non-Distinct Values


I am struggeling a little with trying to write the LINQ query to do the following,

public class MyClass
{
    public int ID {get; set;}
    public int Name {get; set;}
    public IEnumerable<string> SomeIEnumerable {get; set;}
}

I am trying to create the object using LINQ from a DB query that would return something as follows,

ID    Name     SomeString
0     NameA    "MyValue"
1     NameB    "Value1"
1     NameB    "Value2"
2     NameC    "Value"

The LINQ is pretty easy to write as well,

from DataRow row in dataSet.Tables[0].Rows
select new MyClass
{
    ID = (int)row["ID"],
    Name = row["Name"].ToString(),
    SomeIEnumerable = new List<string>{ row["SomeString"].ToString() }
};

The tricky part is how do I turn this into a Dictionary where dictionary[1].SomeIEnumerable = {"Value1", "Value2"}

A simple ToDictionary would throw an ArgumentException

The main issue here, is how do I handle the fact that the keyis not distinct, and be able to lookup in the temporary dictionary the existing value to add to it the values I am interested in.


Solution

  • You can also your grouping, and then use IGrouping to retrieve the list of items in the group

    Sample code

        var simulatedData = Enumerable.Range(0,10).Select(x=> new {Key=x%3+1, Index=x}); 
        var dict = simulatedData.GroupBy(x=>x.Key).ToDictionary(x=>x.Key, x=>x.Select(t=>t.Index));