我反序列化JSON,例如:files = JsonConvert.DeserializeObject<Files>(json);
我想计算 natives-windows 和 artifact ,所以我使用了lamba,但得到了NullReferenceException。
files.libraries.GroupBy(x => new { x.downloads.artifact, x.downloads.classifiers.natives-windows }).Count();
有我的课程:
public class Files
{
public List<Library> libraries { get; set; }
}
public class Library
{
public Downloads downloads { get; set; }
}
public class Downloads
{
public Artifact artifact { get; set; }
public Classifiers classifiers { get; set; }
}
public class Artifact{...}
public class Classifiers
{
public NativesWindows natives-windows { get; set; }
...
}
public class NativesWindows{...}
答案 0 :(得分:0)
我相信您的json数据和您的类之间存在不匹配,因此返回的对象具有空值。
我还相信您的LINQ查询也有问题。
以这种方式尝试。您需要按分组后选择
files.libraries.GroupBy(x => new { x.downloads.artifact,
x.downloads?.classifiers?.natives-windows ?? "default value for nulls" })
.Select(x => new {
Artifact = x.Key.artifact,
NativesWindows = x.Key.natives-windows,
Count = x.Count()
});
请记住,修复LINQ查询不会解决您的NullReferenceException