【问题标题】:Linq count on a secondary grouping criteriaLinq 依靠辅助分组标准
【发布时间】:2020-03-09 23:11:19
【问题描述】:

我需要一个 linq 查询方面的帮助,这让我发疯了。 我有一个包含以下数据的数据表:

Item1 / child1 / 10 列

Item1 / child2 / 10 列

Item2 / child1 / 10 列

Item3 / child1 / 10 列

Item3 / child2 / 10 列

我想要以下结果:

Item1 / 子项数 / child1 / 1 列

Item1 / 子项数 / child2 / 1 列

Item2 / 子项计数 / child1 / 1 列 等等....

在我的查询中,item 是“artiste”,child 是“album”,1 列是“disque”

 var tre_res = from res in Globals.ds.Tables[0].AsEnumerable()
                      orderby res.Field<string>("artiste")
                      group res by new { arti = res.Field<string>("artiste"), alb = res.Field<string>("album") } into groupings
                      select new artisteYalbum { artiste = groupings.Key.arti, album = groupings.Key.alb,  countealb = groupings.Count() };

我有 2 个问题:我无法理解计数的结果,这不是孩子的数量……另外,我不知道如何选择附加列。

这是artisteYalbum 类:

   public class artisteYalbum
{
    public string artiste { get; set; }
    public string album { get; set; }
    public string disque { get; set; }
    public int countealb { get; set; }
}

最终,我希望能够填充树视图并将专辑数量(计数)放在艺术家姓名的末尾(带括号)。此查询将允许我立即输入该计数,而无需计算任何内容。 谢谢

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    从您的示例看来,您实际上并不想对数据库项目进行分组,因为 item1 在结果中出现了两次。看来您需要计算每个艺术家的 albun,并将该值附加到 artisteYalbum 实例。

    试试这个:

    var items = (from res in Globals.ds.Tables[0].AsEnumerable()
                orderby res.Field<string>("artiste")
                select new artisteYalbum
                {
                    artiste = res.Field<string>("artiste"),
                    album = res.Field<string>("album")
                    // additional properties here...
                }).ToList();
    
    // gets the count of albums for each artist
    var counts = items.GroupBy(x => x.artiste)
        .ToDictionary(g => g.Key, g => g.Count());
    
    // fills countealb property value
    foreach (var item in items)
        item.countealb = counts[item.artiste];
    

    【讨论】:

    • 感谢 Thomas,实际上我想要的是计数而不是索引。最终,我想用 2 个级别填充树视图:艺术家和专辑。该计数将用于在艺术家名称末尾添加专辑数量(如“艺术家xx(3)”),添加列将帮助我为每个专辑添加一个图标
    • 嘿,Thomas,在最后一行的“项目”中填回计数之前,它工作得很好。 counts[item.Artiste] 带来了正确的值,但“item.countealb”由于某些原因保持在 0 !
    • 这很奇怪。尝试在代码中放置断点并调试最后一项的“item.countealb”分配,以找出它不工作的原因
    • 我刚刚从答案编辑历史中看到您已经找到了解决方案,只需在items 查询末尾附加“.ToList()”即可!我相应地更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多