【问题标题】:LINQ with groupby and count, plus Name带有 groupby 和 count 的 LINQ,加上 Name
【发布时间】:2021-11-16 12:55:43
【问题描述】:

我想显示一个列表,其中包含所有者名称和每个列表的数量。 group.Key 给了我这个人的 id,但我怎样才能把它换成名字?

// Get all lists owned by an organization
var lists = context.SalesToolsLists.Include(x=>x.OwningUserOrganization).Where(x => uoids.Contains(x.OwningUserOrganization.Id));

// Get a dataset where each row contains OwningUserOrganization.FullName, group.Key and group.Count()
res.UOListCounts = new List<Tuple<int, int>>();
foreach (var listgroup in lists?.GroupBy(info => info.OwningUserOrganizationId).Include(x=>x)
        .Select(group => new
        {
            Metric = group.Key,
            Count = group.Count(),
          
        }).OrderBy(x => x.Metric))
{
    res.UOListCounts.Add(new Tuple<int, int>(listgroup.Metric, listgroup.Count));
}

【问题讨论】:

  • GroupBy(info =&gt; new { id = info.OwningUserOrganizationId, name = info.Name}) 假设名称在 info 变量中
  • 附注(这是我的观点),将查询移出 foreach 并移入自己的变量可能会提高代码的可读性。
  • 感谢所有帮助! gunr2171,没错!

标签: c# linq


【解决方案1】:

您只需按名称而不是OwningUserOrganizationId 对项目进行分组,如下所示:

foreach (var listgroup in lists?.GroupBy(info => info.OwningUserOrganization.FullName).Include(x=>x)
        .Select(group => new
        {
            Metric = group.Key,
            Count = group.Count(),
          
        }).OrderBy(x => x.Metric))
{
    res.UOListCounts.Add(new Tuple<int, int>(listgroup.Metric, listgroup.Count));
}

所以group.Key 给OwningUserOrganization.FullName

正如 @gunr2171 在 cmets 中指出的那样,作为奖励,您可以将查询移出 foreach 并放入其自己的变量中,以提高代码的可读性。

【讨论】:

  • 非常感谢!效果很好!
猜你喜欢
  • 2012-06-24
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2011-03-25
相关资源
最近更新 更多