Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - get total count of values from nested list

Tags:

c#

linq

i have a Class:

public class Company
{
    public int id { get; set; }
    public string title { get; set; }
    public string address { get; set; }
    public string city { get; set; }
    public string zip { get; set; }
    public List<string> phones { get; set; }
    public List<string> categories { get; set; }
}

and i have a Generic List which contains that Class:

public List<Company> Companies = new List<Company>();

i want to do two things:

  1. get a distinct list of the categories
  2. get a total count of companies per category

i think i managed to the the first thing:

Companies.SelectMany(c => c.categories).Distinct() please tell me if you think anything is wrong with that.

i tried the second step as so: Companies.SelectMany(c => c.categories).Where(c=>c == Category).Count() but im not sure that is really right.

like image 807
Rafael Herscovici Avatar asked Sep 18 '11 15:09

Rafael Herscovici


2 Answers

  1. Correct

  2. You need to flatten the list into (company, category) pairs, then group by category:

    from company in Companies
    from category in company.Categories
    group company by category into g
    select new { Category = g.Key, Count = g.Count() }
    

    EDIT: If you want to find out how many companies are in a single given category, you can write

    Companies.Count(c => c.Categories.Contains(categoryName))
    
like image 64
SLaks Avatar answered Nov 07 '22 11:11

SLaks


Companies
    .SelectMany(c => c.categories)
    .GroupBy(c => c)
    .Select(g => new 
        {
            Cateogry = g.Key, 
            Count = g.Count()
        });

If you want it for specific category then your query is correct already.

like image 33
Muhammad Hasan Khan Avatar answered Nov 07 '22 09:11

Muhammad Hasan Khan