首页 > 解决方案 > linq计数二次分组和计数不分组

问题描述

我正在尝试构建一个用于统计的摘要查询。

我有一个带有以下列的数据表(大约 18000 行):

Artist / Album / file_path (one for each song) / rating / 

每个艺术家都有 1 个或多个包含歌曲的专辑,每首歌曲都有评分

我想得到以下结果:

对于每个艺人ID(比艺人名更可靠),专辑总数、歌曲总数、评分总数等于5。

Artist x / #album / #songs / #rating = 5 / song.first() //in song.first i have access to the file path, it can be any file path from the artist hence the first one.

我已经拉了几个小时的头发,但我无法获得每位艺术家的专辑数量:(这是我迄今为止一直在尝试的:

我有一个查询类:

  public class art_detail
    {
        public string artiste { get; set; }
        public string fp { get; set; } // the file_path
        public int nbr_album { get; set; }
        public int nbr_song { get; set; }
        public int nbr_rat5 { get; set; }
    }

这是我提出的查询:

            var result = from res in Globals.ds.Tables[0].AsEnumerable() // the table
           .GroupBy(x =>  new { art = x.Field<int>("Artist_ID"), alb = x.Field<string>("album") })
           .Select(x => new art_detail { artiste = x.Select(p =>p.Field<string>("artiste")).First(), fp = x.Select(p=>p.Field<string>("file_path")).First(), nbr_album = x.Key.alb.Count() })
           .OrderBy(x => x.artiste)
                  select res;

不幸的是,计数完全错误,我不知道如何获得评分 = 5 :(

谢谢您的帮助 !

编辑:这是我让它工作的查询:

               var table = Globals.ds.Tables[0].AsEnumerable();
               var stats = table.GroupBy(x => x.Field<int>("Artist_ID"))
                .Select(x => new art_detail
                {
                     artiste = x.Select(p=>p.Field<string>("artiste")).First(),
                     nbr_album = x.Select(y => y.Field<string>("album")).Distinct().Count(),
                     fp = x.Select(y => y.Field<string>("file_path")).FirstOrDefault(),
                     nbr_song = x.Count(),
                     nbr_rat5 = x.Count(y => y.Field<int>("Rating") == 5)
                 });

比我想象的要简单:)

标签: c#winformslinq

解决方案


假设一个表的模式与此类匹配:

public class Song
{
    public string ArtistID { get; set; }
    public string Album { get; set; }
    public string FilePath { get; set; }
    public int Rating { get; set; }
}

并给定一个 LINQ 源,您有以下查询:

IQueryable<Song> table = /*insert source*/;
var stats = table.GroupBy(x => x.ArtistID);
                 .Select(x => new art_detail
                 {
                     artiste = x.Key,
                     nbr_album = x.Select(y => y.Album).Distinct().Count(),
                     nbr_song = x.Count(),
                     nbr_rat5 = x.Count(y => y.Rating == 5),
                 });

推荐阅读