我有两节课:
public GeneralClassName
{
public GeneralClassName ()
{
SpecificList = new List<OtherClass>();
}
public string StringValue;
public string OtherStringValue;
public List<OtherClass> SpecificList;
}
Run Code Online (Sandbox Code Playgroud)
和
public OtherClass
{
public string Name;
public string Number;
}
Run Code Online (Sandbox Code Playgroud)
一个反序列化JSON我得到一个不错后List<GeneralClassName>,结果我要的是Dictionary<string, int>它的值是variabiles的总和"数"内List<OtherClass>内List<GeneralClassName>,而关键是variabile的名称.
换句话说,我想按名称对数字分组进行总结.
现在,我唯一想到的就是嵌套的foreach,类似的东西:
Dictionary<string, int> resultDictionary = new Dictionary<string, int>();
foreach(List<OtherClass> listOtherClass in bigListGeneralClass.Select(x => x.SpecificList))
{
foreach(OtherClass otherClass in listOtherClass)
{
int value = 0;
if(resultDictionary.ContainsKey(otherClass.Name))
{
resultDictionary[otherClass.Name] += otherClass.Number;
}
else
{
resultDictionary.Add(otherClass.Name, otherClass.Number);
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然这个解决方案似乎运作良好,但我根本不喜欢它.有没有更简洁的方法来找到这个结果?也许通过一个很好的LINQ查询?
由于您不使用任何信息,GeneralClassName您可以使用它SelectMany来展平您的列表.这个OtherClass实例的平面列表按Name属性分组.最后,将组列表转换为字典,其中组的键(也称为Name属性)是新属性的键,值是该Number组中所有值的总和:
var result = bigListGeneralClass.SelectMany(x => x.SpecificList)
.GroupBy(x => x.Name)
.ToDictionary(x => x.Key,
x => x.Sum(y => y.Number));
Run Code Online (Sandbox Code Playgroud)
此代码假定OtherClass.Number实际上int不是a string.这个假设也用在带循环的示例代码中.
如果此假设不正确,请更改y.Number为int.Parse(CultureInfo.InvariantCulture, y.Number).
注意:如果无法解析任何数字,则会抛出异常,因此您可能需要事先确保所有数字都包含有效数字.