Search code examples
c#linq

LINQ with multi list class


I have the following class to get an API response:

    [JsonObject]
    [Serializable]
    public class Root
    {
        public Metadata metadata {  get; set; }
        public List<Result> result { get; set; }
    }

    [JsonObject]
    [Serializable]
    public class GroupRecord
    {
        public string groupNumber { get; set; }
    }

    [JsonObject]
    [Serializable]
    public class Metadata
    {
        public int totalCount { get; set; }
        public int page { get; set; }
        public int pageCount { get; set; }
    }

    [JsonObject]
    [Serializable]
    public class Npi
    {
        public DateTime EffectiveDate { get; set; }
    }

    [JsonObject]
    [Serializable]
    public class Result
    {
        public string Name { get; set; }
        public Npi npi { get; set; }
        public List<GroupRecord> aGroupRecord { get; set; }
    }

I'm trying to get the result that matches a given groupNumber and has the latest EffectiveDate with LINQ.

Here is my application code that I thought should work:

string groupNumber = "SALT"
Root dataObject = response.Content.ReadAsAsync<Root>().Result;
if (dataObject.result.Count >= 1)
{
    var result = dataObject.result.Where(x => x.aGroupRecord.Where(a => a.groupNumber == groupNumber).OrderByDescending(x.npi => x.npi.EffectiveDate)).FirstOrDefault();
}

Solution

  • If the output should be a Result, then you want:

    Result result = dataObject.result
        .Where(r => r.aGroupRecord.Any(gr => gr.groupNumber == groupNumber))
        .OrderByDescending(r => r.npi.EffectiveDate)
        .FirstOrDefault();
    

    I'm not using x as a parameter name to make it more clear what the parameter represents: r for "record" and gr for "groupRecord".

    This assumes that, during the filtering process, you want to keep any Record object that has at least one GroupRecord object with the matching group number.

    Your code had some shenanigans happening with the .OrderByDescending(x.npi. It was attached to x.aGroupRecord, but it was reusing a variable higher up in the scope.