LINQ Help

Soldato
Joined
27 Mar 2003
Posts
2,710
Ok you could try something like this then:

This is untested by the way

Code:
	 db.SubCategories.GroupBy(subcategory => subcategory.Category.Description).
	   Select(groupedCategory => new 
{
 CategoryDescription =  groupedCategory.Key
, TotalNumberOfProjects =  groupedCategory.Sum(subcategory.ProjectCategories.Any() ? subcategory.ProjectCategories.Count() : 0) 
}  
).ToList()


So we do the grouping first on your category name and then total up the number of projects afterwards.

I haven't used the GroupBy in LINQ too much and if I do it is usually to get something simple. Like a list of strings etc.

Hope this helps. (I'm still picking up LINQ myself)
 
Associate
OP
Joined
25 Feb 2007
Posts
905
Location
Midlands
Works like a charm! Thanks very much! :D

Your last bit of code was almost what I had, but I was missing the use of Any() and the conditional operator.

Thanks for your help again!
 
Soldato
Joined
27 Mar 2003
Posts
2,710
Not a problem. My development skills must be improving to be able to do this without any sort of development tools. :p

Glad you got it sorted.

If you have any other issues just give me a shout.
 
Associate
OP
Joined
25 Feb 2007
Posts
905
Location
Midlands
I have another question, which is related!

My whole system revolves around filtering the set of Projects by various properties, so I have a method that applies all the filters and returns a list of Project objects.

This is used in a few places - I want to also use it in what I've been doing above.

As it's a list of Projects, I think I need to Join it to the SubCategories, so I have the following:
Code:
db.SubCategories.Join(GetProjects(), subcat => subcat.ProjectCategories.Select(projcat => projcat.ProjectID), proj => proj.ID, (projcat, proj) => new {projcat, proj}).GroupBy(out => out.cs.Category.Description)
                .Select(groupedCat => new
                {
                    CategoryName = groupedCat.Key,
                    NumberOfProjects = groupedCat.Count()
                }
            );

However I'm getting an error:
The type arguments for method 'System.Linq.Enumerable.Join<TOuter,TInner,TKey,TResult>(System.Collections.Generic.IEnumerable<TOuter>, System.Collections.Generic.IEnumerable<TInner>, System.Func<TOuter,TKey>, System.Func<TInner,TKey>, System.Func<TOuter,TInner,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

This bit subcat.ProjectCategories.Select(projcat => projcat.ProjectID) seems to be causing the error, and I think it's because I'm having go through another entity to get the ID I need (e.g. if I could just do subcat.ProjectID, then it would work fine.)

Am I even on the right track? Any ideas?

Thanks! :D
Matt
 
Back
Top Bottom