Reputation: 886
I have a simple custom object:
class CertQuestion
{
public string Field {get;set;}
public string Value {get;set;}
}
Subsequently I find myself with a List in some code. I'm trying to figure out how to format a list of CertQuestions into a corresponding Dictionary with similar Field names grouped together. For instance, given the following list:
List<CertQuestion> certQuestions = new List<CertQuestion>()
{
new CertQuestion("Key", "Value1"),
new CertQuestion("Key", "Value2"),
new CertQuestion("Key2", "Value"),
new CertQuestion("Key2", "Value2")
};
I would like to convert that (trying to use LINQ) into a Dictionary with two entries such as
{{"Key", "Value1, Value2"}, {"Key2", "Value, Value2"}}
Upvotes: 1
Views: 9311
Reputation: 1714
Group the questions by field, then convert to dictionary by selecting key, then value. Value becomes the grouping's list.
certQuestions.GroupBy(c => c.Field)
.ToDictionary(k => k.Key, v => v.Select(f => f.Value).ToList())
Or for an array:
certQuestions.GroupBy(c => c.Field)
.ToDictionary(k => k.Key, v => v.Select(f => f.Value).ToArray())
Edit based on question in comment:
class CertTest
{
public string TestId {get;set;}
public List<CertQuestion> Questions {get;set;}
}
var certTests = new List<CertTest>();
You would use the SelectMany extension method. It is designed to aggregate a property list object that is in each element of the original list:
certTests.SelectMany(t => t.Questions)
.GroupBy(c => c.Field)
.ToDictionary(k => k.Key, v => v.Select(f => f.Value).ToList())
Upvotes: 13
Reputation: 136074
Your requirement was for a comma-separated list of values, that can be done like this:
var dict = certQuestions.GroupBy(c => c.Field)
.ToDictionary(k => k.Key, v => String.Join(", ", v.Select(x => x.Value)))
Live example: http://rextester.com/LXS58744
(You should consider whether what you actually want is the values to be an Array
or List<string>
- see other answers)
Upvotes: 3