c# linq one to many filter by child property

Viewed 54

I have a product model class with many versions childs:


public class Product {
  public int Id {
    get;
    set;
  }

  public string Name {
    get;
    set;
  } = "";
  public List <Version> Versions {
    get;
    set;
  } = new List <Version> ();
}

public class Version {
  public int Id {
    get;
    set;
  }

  public string Name {
    get;
    set;
  } = "";
  public DateTime ReleaseDate {
    get;
    set;
  } = new DateTime();
}

I want to filter by a child property: releasedate:

var releaseDateFrom = DateTime.ParseExact("20110720", "yyyyMMdd", CultureInfo.InvariantCulture);
      
    var products = ProductRepository.GetAll();
    List <ProductDto> list;
    list = products.Where(
      p => (p.Name!.StartsWith("p") &&
        p.Name!.Length > 0) &&
        GetReleaseDateFromVersion(p.Versions.OrderBy(p => p.ReleaseDate).LastOrDefault()) > releaseDateFrom
    ).Select(p =>
      new ProductDto {
        Id = p.Id,
          Name = p.Name,
          LatestVersionDate = GetReleaseDateFromVersion(p.Versions.OrderBy(p => p.ReleaseDate).LastOrDefault())
      }).ToList();
      
    DateTime GetReleaseDateFromVersion(Version v) => v == null ? new DateTime() : v.ReleaseDate;
    
    list.ForEach(p => Console.WriteLine("{0} {1}", p.Name, p.LatestVersionDate));

The result output shows that the filter date > 20 July 2022 does not work:

product 1 11/20/2013 00:00:00
product 2 06/20/2013 00:00:00

Product 2 should not be listed.

What am I doing wrong? Any suggestions how to fix this query?

The code can be run here: https://dotnetfiddle.net/esRdOg

Edit after comment from @SergeySosunov

As @SergeySosunov correctly noted: My filter date was wrong. The above code works as expected.

0 Answers
Related