将List转换为Dictionary <string,string []>

Nat*_*222 -1 .net c#

我有一个简单的自定义对象:

class CertQuestion
{
    public string Field {get;set;}
    public string Value {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

随后我发现自己在一些代码中使用了List.我正在试图弄清楚如何将CertQuestions列表格式化为相应的字典,并将类似的字段名称组合在一起.例如,给出以下列表:

        List<CertQuestion> certQuestions = new List<CertQuestion>()
            {
                new CertQuestion("Key", "Value1"),
                new CertQuestion("Key", "Value2"),
                new CertQuestion("Key2", "Value"),
                new CertQuestion("Key2", "Value2")
            };
Run Code Online (Sandbox Code Playgroud)

我想将它(尝试使用LINQ)转换为带有两个条目的字典,例如

{{"Key", "Value1, Value2"}, {"Key2", "Value, Value2"}}
Run Code Online (Sandbox Code Playgroud)

rcl*_*ent 7

按字段对问题进行分组,然后通过选择键,然后选择值转换为字典.值成为分组列表.

certQuestions.GroupBy(c => c.Field)
             .ToDictionary(k => k.Key, v => v.Select(f => f.Value).ToList())
Run Code Online (Sandbox Code Playgroud)

或者对于一个数组:

certQuestions.GroupBy(c => c.Field)
             .ToDictionary(k => k.Key, v => v.Select(f => f.Value).ToArray())
Run Code Online (Sandbox Code Playgroud)

根据评论中的问题进行修改:

class CertTest 
{
    public string TestId {get;set;}
    public List<CertQuestion> Questions {get;set;}
}
var certTests = new List<CertTest>();
Run Code Online (Sandbox Code Playgroud)

您将使用SelectMany扩展方法.它旨在聚合原始列表的每个元素中的属性列表对象:

certTests.SelectMany(t => t.Questions)
         .GroupBy(c => c.Field)
         .ToDictionary(k => k.Key, v => v.Select(f => f.Value).ToList())
Run Code Online (Sandbox Code Playgroud)

  • 不太对,那会给你一个`Dictionary <string,List <CertQuestion >>`.你需要'选择'`值`.像`.ToDictionary(k => k.Key,v => v.Select(cq => cq.Value).ToList()) (2认同)