Reputation: 4795
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.
Upvotes: 1
Views: 1629
Reputation: 4795
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()
};
Upvotes: 1
Reputation: 30698
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));
Upvotes: 3