[英]How to do in this in Linq C#
So far, I have this: 到目前为止,我有这个:
var v = Directory.EnumerateFiles(_strConfigurationFolder)
.GroupBy(x => GetReportName(Path.GetFileNameWithoutExtension(x)));
Configuration folder will contain pairs of files: 配置文件夹将包含文件对:
abc.json
abc-input.json
def.json
def-input.json
GetReportName() method strips off the "-input" and title cases the filename, so you end up with a grouping of: GetReportName()方法去除了“ -input”和标题大小写的文件名,因此最终得到以下分组:
Abc
abc.json
abc-input.json
Def
def.json
def-input.json
I have a ReportItem class that has a constructor (Name, str1, str2). 我有一个具有构造函数(名称,str1,str2)的ReportItem类。 I want to extend the Linq to create the ReportItems in a single statement, so really something like: 我想扩展Linq以在单个语句中创建ReportItems,所以实际上是这样的:
var v = Directory.EnumerateFiles(_strConfigurationFolder)
.GroupBy(x => GetReportName(Path.GetFileNameWithoutExtension(x)))
**.Select(x => new ReportItem(x.Key, x[0], x[1]));**
Obviously last line doesn't work because the grouping doesn't support array indexing like that. 显然,最后一行不起作用,因为分组不支持这种数组索引。 The item should be constructed as "Abc", "abc.json", "abc-input.json", etc. 该项目应构造为“ Abc”,“ abc.json”,“ abc-input.json”等。
If you know that each group of interest contains exactly two items, use First()
to get the item at index 0, and Last()
to get the item at index 1: 如果您知道每个感兴趣的组恰好包含两个项目,请使用First()
获取索引0处的项目,并使用Last()
获取索引1处的项目:
var v = Directory.EnumerateFiles(_strConfigurationFolder)
.GroupBy(x => GetReportName(Path.GetFileNameWithoutExtension(x)))
.Where(g => g.Count() == 2) // Make sure we have exactly two items
.Select(x => new ReportItem(x.Key, x.First(), x.Last()));
var v = Directory.EnumerateFiles(_strConfigurationFolder)
.GroupBy(x => GetReportName(Path.GetFileNameWithoutExtension(x))).Select(x => new ReportItem(x.Key, x.FirstOrDefault(), x.Skip(1).FirstOrDefault()));
But are you sure there will be exactly two items in each group? 但是,您确定每个组中将恰好有两个项目吗? Maybe has it sence for ReportItem to accept IEnumerable, not just two strings? 也许ReportItem可以接受IEnumerable,而不仅仅是两个字符串?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.