简体   繁体   中英

LINQ - get total count of values from nested list

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.

  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)) 
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM