c# - 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)
});
比我想象的要简单:)
解决方案
假设一个表的模式与此类匹配:
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),
});
推荐阅读
- python-3.x - 如何使用selenium python打开新的聊天whatsapp(我需要针对第二个图标New Chat)
- python - 带有熊猫的日期正则表达式过滤器不起作用
- objective-c - tvOS - 聚焦时更改 UICollectionViewCell 的宽度
- python - 具有单场渲染和功能的模态弹出窗口,但不提交?
- api - 如何将 nginx 路径从“http://domain/api/path”重写为“http://domain”
- c# - DataTable AsEnumerable 上的 LINQ 查询返回 null
- c++ - 模板函数中从 'const int*' 到 'int*' 的无效转换
- java - 如何从现有文件夹结构创建 Maven 项目?
- javascript - 我正在尝试向对象添加属性,但只有最后一个被附加
- python - 使用 pandas python 将使用 date_range 生成的索引添加到数据框