Nested linq queries, how to get individual values?

table data from 2 columns "category" and "subcategory"

I want to get a collection of "category", [subcategories] using the code below, I get duplicates. Puting.Distinct () after the external "from" does not help much. What am I missing?

 var rootcategories = (from p in sr.products
                                 orderby p.category
                                  select new
                                  {
                                      category = p.category,
                                      subcategories = (
                                      from p2 in sr.products
                                      where p2.category == p.category
                                      select  p2.subcategory).Distinct()
                                  }).Distinct();

sr.products is as follows

category   subcategory
----------------------
cat1       subcat1
cat1       subcat2
cat2       subcat3
cat2       subcat3

what i get in the results

cat1, [subcat1,subcat2]
cat1, [subcat1,subcat2]

but I want only one entry

solved my problem with this code:

   var rootcategories2 = (from p in sr.products
                               group p.subcategory by p.category into subcats

                               select subcats);

Now, maybe it's time to think about what the right question was .. (-:

+5
source share
4 answers

resolved using this code

   var rootcategories2 = (from p in sr.products
                               group p.subcategory by p.category into subcats

                               select subcats);

thanks everyone

+5
source

, 2 "Distinct()", .

:

var mainCategories = (from p in products select p.category).Distinct();

var rootCategories =
    from c in mainCategories
    select new {
        category = c,
        subcategories = (from p in products
                         where p.category == c
                         select p.subcategory).Distinct()
    };
+3

Distinct() , 2 IEnumerable. , 2 , , "", "" .

, , IEnumerable Distinct().

+2

"", . , , Product.Category

+1

All Articles