如何创建与JSON对象中的ID匹配的记录列表?

时间:2016-12-20 16:51:38

标签: c# json

我有以下JSON对象(SoftwareImageTestPlans)作为我的API的输入,我正在尝试创建一个与SoftwareImageTestPlans_WithParticularSoftwareImageID = SoftwareImageTestPlans.Select(c => c.SoftwareImageID == SoftwareImageID);行匹配的SoftwareImageID匹配的所有SoftwareImageTestPlans的记录,它似乎没有工作,因为它抛出一个我以后尝试检索数据时出错,如何修复此错误?

SoftwareImageTestPlans :
[
  {
    "SoftwareImageTestPlanID": 0,
    "SoftwareImageID": 0,
    "SoftwareImage": "string",
    "TestPlanMasterID": 0,
    "TestPlanVersionID": 0,
    "TestPlanName": "string",
    "TCIndexList": "string",
    "TCNamesList": "string"
  },
  {
    "SoftwareImageTestPlanID": 1,
    "SoftwareImageID": 1,
    "SoftwareImage": "string",
    "TestPlanMasterID": 0,
    "TestPlanVersionID": 0,
    "TestPlanName": "string1",
    "TCIndexList": "string1",
    "TCNamesList": "string1"
  },
  {
    "SoftwareImageTestPlanID": 0,
    "SoftwareImageID": 0,
    "SoftwareImage": "string",
    "TestPlanMasterID": 0,
    "TestPlanVersionID": 0,
    "TestPlanName": "string1",
    "TCIndexList": "string1",
    "TCNamesList": "string1"
  }
]

API:

public List<SoftwareImageTestPlan> AddOrUpdate(List<SoftwareImageTestPlan> SoftwareImageTestPlans)
{
    // List<int> BuildList = new List<int>();
    IEnumerable<bool> SoftwareImageTestPlans_WithParticularSoftwareImageID = new List<bool>();

    foreach (var SoftwareImageID in SoftwareImageTestPlans.Select(sid => sid.SoftwareImageID).Distinct())
    {
        Console.WriteLine(SoftwareImageID);
         SoftwareImageTestPlans_WithParticularSoftwareImageID = SoftwareImageTestPlans.Select(c => c.SoftwareImageID == SoftwareImageID);
    }

    foreach (var SoftwareImageTestPlan in SoftwareImageTestPlans_WithParticularSoftwareImageID)
    {
        Console.WriteLine(SoftwareImageTestPlan.SoftwareImageID); //Throw the error mentioned below
    }
    return null;
}   

错误: -

'bool' does not contain a definition for 'SoftwareImageID' and no extension method 'SoftwareImageID' accepting a first argument of type 'bool' could be found

1 个答案:

答案 0 :(得分:0)

我认为问题在于:

foreach (var SoftwareImageTestPlan in SoftwareImageTestPlans_WithParticularSoftwareImageID)
{
    Console.WriteLine(SoftwareImageTestPlan.SoftwareImageID); //Throw the error mentioned below
}

您正在迭代bool列表,因此在该foreach中变量SoftwareImageTestPlan的类型为bool,因此它没有SoftwareImageID。

为此,您可以将SoftwareImageTestPlans_WithParticularSoftwareImageID的类型更改为IEnumerable of SoftwareImageTestPlan

并更改行

SoftwareImageTestPlans_WithParticularSoftwareImageID = SoftwareImageTestPlans.Select(c => c.SoftwareImageID == SoftwareImageID);

SoftwareImageTestPlans_WithParticularSoftwareImageID = SoftwareImageTestPlans.Where(c => c.SoftwareImageID == SoftwareImageID);