开发者

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() bu开发者_开发百科t 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜