1

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.

Tilak
  • 30,108
  • 19
  • 83
  • 131
M Afifi
  • 4,645
  • 2
  • 28
  • 48

3 Answers3

3

Instead of calling ToDictionary, call ToLookup. :)

Roman
  • 19,581
  • 6
  • 68
  • 84
leppie
  • 115,091
  • 17
  • 196
  • 297
3

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));
Tilak
  • 30,108
  • 19
  • 83
  • 131
1

Answer thanks to @Tilak is,

from DataRow row in dataSet.Tables[0].Rows
group row by new
{
    ID = (int) row["ID"],
    Name = row["Name].ToString()
} into rowGroup
select new MyClass
{
    ID = rowGroup.Key.ID,
    Name = rowGroup.Key.Name,
    SomeIEnumerable =
        from row in rowGroup
        select row["SomeString"].ToString()
};
M Afifi
  • 4,645
  • 2
  • 28
  • 48