gpt4 book ai didi

c# - 无法转换类型为 'System.Linq.GroupedEnumerable to type ' System.Collections.Generic.List 的对象

转载 作者:太空宇宙 更新时间:2023-11-03 19:16:42 25 4
gpt4 key购买 nike

我有这样的类(class)。

 public static SkillViewModel GetAllList(string ID)
{
ListViewModel viewModel = new ListViewModel();
DataTable dt = DAL.GetAllList(ID);

List<Skill> skills = new List<Skill>();
foreach (DataRow row in dt.Rows)
{
Skill skill = new Skill() { GroupName = row["GroupName"] != null ? row["GroupName"].ToString() : string.Empty, SubName = row["SubName"] != null ? row["SubName"].ToString() : string.Empty};
skills.Add(skill);
}
viewModel.skills = skills;
viewModel.skills = skills.GroupBy(x => x.GroupName); //Showing error in this line
return viewModel;

}

还有一个是这样的:

 public class SkillViewModel
{
public List<Skill> skills { get; set; }
}

public class Skill
{
[DisplayName("Sub Name")]
[Required]
public string SubName { get; set; }

[DisplayName("Group Name")]
[Required]
public string GroupName { get; set; }
}

但是它通过说

失败了

Error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable>' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

请帮助。提前致谢。

最佳答案

只需添加 ToListSelectMany在语句的末尾,如:

viewModel.skills = skills.GroupBy(x => x.GroupName).SelectMany(r => r).ToList();

使用 SelectMany会使组变平,不确定为什么要对数据进行分组,而您的属性是 List<Skill>

关于c# - 无法转换类型为 'System.Linq.GroupedEnumerable to type ' System.Collections.Generic.List 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com