C# 将一个平面类型的列表转换为另一个层次类型的最佳算法#

C# 将一个平面类型的列表转换为另一个层次类型的最佳算法#,c#,linq,.net-core,C#,Linq,.net Core,我有一个类Type1,看起来像这样 public Class Type1{ public string Key {get; set; } public List<string> Values {get; set; } } 最终结果应该是这样 [ { "key": "Key1", "values": ["value1","value2"

我有一个类Type1,看起来像这样

public Class Type1{
   public string Key {get; set; }
   public List<string> Values {get; set; }
}
最终结果应该是这样

[
  {
    "key": "Key1",
    "values": 
        ["value1","value2"]
  },
  {
    "key": "Key2",
    "values": ["value2"]
  }
]

我试图在这里使用linq字典,但没有得到我想要的。

仅使用linq会使它无法阅读。答案应该是这样的:

List<Type1> input = ...;

var resultDictionary = new Dictionary<string, List<string>>();
foreach (var item in input)
{
    List<string> value;
    if (resultDictionary.TryGetValue(item.Key, out value))
        value.Add(item.Values[0]);
    else
        resultDictionary.Add(item.Key, new List<string>() { item.Values[0] });
}

return resultDictionary.Select(x => new Type1() { Key = x.Key, Values = x.Value }).ToList();
列表输入=。。。;
var resultDictionary=新字典();
foreach(输入中的变量项)
{
列表值;
if(resultDictionary.TryGetValue(item.Key,out值))
增值(项目价值[0]);
其他的
resultDictionary.Add(item.Key,new List(){item.Values[0]});
}
返回resultDictionary.Select(x=>newtype1(){Key=x.Key,Values=x.Value}).ToList();

您能告诉我们到目前为止您尝试了什么吗;您可以尝试:遍历平面列表;如果第二个列表已经具有列表1中的键,则将其添加为子项,否则将其添加为父项。最初,第二个列表是空的,因此它也将添加第一个项目。这篇文章可能会对您有所帮助。我建议你把问题分开。编写一个将单个项转换为层次项的方法。然后编写一个for循环,为列表中的所有元素调用此函数。我使用automapper将Type1转换为Type2,使用重复的键,但Values属性中只有一项。有没有办法将这些合并到一个列表中。例如,映射后的列表具有key1-->(值属性中的单个项)Value1、key1-->(值属性中的单个项)Value2。我们如何迭代或使用Linq将它们合并到Key1--->Value1,Value2
List<Type1> input = ...;

var resultDictionary = new Dictionary<string, List<string>>();
foreach (var item in input)
{
    List<string> value;
    if (resultDictionary.TryGetValue(item.Key, out value))
        value.Add(item.Values[0]);
    else
        resultDictionary.Add(item.Key, new List<string>() { item.Values[0] });
}

return resultDictionary.Select(x => new Type1() { Key = x.Key, Values = x.Value }).ToList();