Looking to query a list of objects based on a property and value in list

I have the following JSON that gets put into a list of objects. Each object has one property and a list of codes. I’m struggling to figure out a way to query the list to find a specific code value for a specific company. I’m ultimately looking for the “AbsenceType” value based on the Company/PayCode. This is what I’ve tried to look at but it’s not working. Looking for any suggestions.

companyAbsenceType = AbsenceCodesList.First(c => 
    (c.Company == companyCode) && (c.Codes.Find(x => x.PayCode == ppc.PayCode));

companyAbsenceType = AbsenceCodesList.Select(c =>
   c.Company == companyCode && c.Codes.Find(x => x.PayCode == ppc.PayCode)).FirstOrDefault();

JSON:

[
  {
    "Company": "Company1",
    "Codes": [
      {
        "PayCode": "SCK",
        "AbsenceType": "Illness"
      },
      {
        "PayCode": "VAC",
        "AbsenceType": "Vacation"
      },
      {
        "PayCode": "BRV",
        "AbsenceType": "Bereavement"
      },
      {
        "PayCode": "JUR",
        "AbsenceType": "Jury Duty"
      },
      {
        "PayCode": "PER",
        "AbsenceType": "Personal"
      }
    ]
  },
  {
    "Company": " Company2",
    "Codes": [
      {
        "PayCode": "SCK",
        "AbsenceType": "Sick"
      },
      {
        "PayCode": "VAC",
        "AbsenceType": "Vacation"
      },
      {
        "PayCode": "BRV",
        "AbsenceType": "Bereavement"
      },
      {
        "PayCode": "JUR",
        "AbsenceType": "Jury Duty"
      },
      {
        "PayCode": "PER",
        "AbsenceType": "Personal"
      },
      {
        "PayCode": "PRNU",
        "AbsenceType": "Personal"
      }
    ]
  }
]

public class AbsenceCodes
    {
        public string Company { get; set; }
        public List<AbsenceCode> Codes { get; set; }
    }
public class AbsenceCode
    {
        public string PayCode { get; set; }
        public string AbsenceType { get; set; }
    }

UPDATE Thanks to Moho and Eric Magers pointing me to a query. The query from Moho worked.

var absenceType = AbsenceCodesList.FirstOrDefault(c => c.Company == companyCode && c.Codes.Any(x => x.PayCode == ppc.PayCode)) ?.Codes.First(c => c.PayCode == ppc.PayCode) ?.AbsenceType;


Solution 1:

You were close, use .Any instead of .Find for the Codes when filtering:

var absenceType = AbsenceCodesList
    // first find a valid top level item
    .FirstOrDefault(c => 
        // is specific company
        c.Company == companyCode
        // has the target paycode
        && c.Codes.Any(x => x.PayCode == ppc.PayCode))

    // then select the desired value
    ?.Codes.First(c => c.PayCode == ppc.PayCode)
    .AbsenceType;