none
How do I do this in LINQ RRS feed

  • Question

  • Hi there, I am looking to do a bunch of counts in Linq which involves multiple tables. I am new to linq and from what I found so far the below may be possible. I have tried this query in LinqPad and it does execute.

    What I am looking to do is filter a count by the related data in the join table. So in the below example filter by Owner PurchaseDate.

    I hope I am explaining myself correctly, would be happy to answer any questions.

    Thanks in advance!

    	from s in Cars
    	join Owner in Owners on s.OwnerId equals Owner.ID into ownerGrp
    	join Model in Models on s.ID equals Model.ID into modelGrp
    	group s by new {s.Year}
    	into g
    	select new
    	{
    		Count1 = g.Count(x => x.Status != "Sold"),
                    Count2 = // Code here that will allow me to use "ownerGrp" purchase date. example if Purchase date is less than 1/1/2029
    	}

    Friday, June 7, 2019 1:29 PM

Answers

  • Maybe like this:

    from car in Cars

    join Owner in Owners on car.OwnerId equals Owner.ID into owners

    join Model in Models on car.ID equals Model.ID into models

    select new { car, owners }

    into data

    group data by data.car.Year

    into g

    select new

    {

        Count1 = g.Count( d => d.car.Status != "Sold" ),

        Count2 = g.Sum( d => d.owners.Where( o => o.PurcacheDate < some_date ).Count( ) )

    };

    • Marked as answer by MVCNewb Thursday, July 4, 2019 1:06 PM
    Saturday, June 8, 2019 8:02 AM

All replies

  • Maybe like this:

    from car in Cars

    join Owner in Owners on car.OwnerId equals Owner.ID into owners

    join Model in Models on car.ID equals Model.ID into models

    select new { car, owners }

    into data

    group data by data.car.Year

    into g

    select new

    {

        Count1 = g.Count( d => d.car.Status != "Sold" ),

        Count2 = g.Sum( d => d.owners.Where( o => o.PurcacheDate < some_date ).Count( ) )

    };

    • Marked as answer by MVCNewb Thursday, July 4, 2019 1:06 PM
    Saturday, June 8, 2019 8:02 AM
  • Thanks! I will try this out.
    Monday, June 10, 2019 12:21 PM