C# i分组,选择“关键点到新类型”,然后选择“Manny(值)”到新集合类型
我正在尝试通过C# i分组,选择“关键点到新类型”,然后选择“Manny(值)”到新集合类型,c#,linq,group-by,C#,Linq,Group By,我正在尝试通过GroupBy字段,选择键进入一个新类型(国家),然后选择多个进入一个新集合类型(国家前缀) 凭直觉,我想到了以下几点,然而,我很难“达成交易” 给定以下类 public class TempPrefix { public String CountryName { get; set; } public String Prefix { get; set; } public int ClassificationId { get; set; } } 而tempP
GroupBy
字段,选择
键进入一个新类型(国家),然后选择多个
进入一个新集合类型(国家前缀)
凭直觉,我想到了以下几点,然而,我很难“达成交易”
给定以下类
public class TempPrefix
{
public String CountryName { get; set; }
public String Prefix { get; set; }
public int ClassificationId { get; set; }
}
而tempPrefixes
是一个列表
SelectMany上的编译错误
方法的类型参数
'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable,
System.Func>)'
无法从用法推断。尝试指定类型参数
明确地说
我肯定这告诉了我一些事情,但我不太确定这是什么
回答
A在接受的答案中指出,我只需要使用Select
而不是SelectMany
此外,我还必须将结果转换为列表
var countries = tempPrefixes
.GroupBy(x => x.CountryName)
.Select(x => new Country
{
Name = x.Key,
CountryPrefixes = x.Select(y => new CountryPrefix
{
ClassificationId = y.ClassificationId,
Prefix = y.Prefix
}).ToList()
});
尝试将其改为选择
在
x已经是相应组下的TempPrefix
的集合,因此您只需通过选择
var countries = tempPrefixes
.GroupBy(x => x.CountryName)
.Select(x => new Country
{
Name = x.Key,
CountryPrefixes = x.Select(y => new CountryPrefix
{
ClassificationId = y.ClassificationId,
Prefix = y.Prefix
}).ToList()
});
CountryPrefixes = x.SelectMany(y => new CountryPrefix
{
ClassificationId = y.ClassificationId,
Prefix = y.Prefix
})