You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#报错CS0029:无法将IEnumerable<string>隐式转换为string问题求解

问题原因

错误CS0029的核心原因是类型不匹配:Distinct()返回的是IEnumerable<string>类型的字符串集合,而numberOne类的Name属性是单个string类型,两者无法直接赋值。
除此之外你的代码还有三处隐性问题:

  • numberTwo集合初始化语法错误,数组赋值需要用{}包裹元素,且多个元素之间缺了逗号
  • 给Names赋值的代码里Distinct后面缺了(),会报委托转换错误
  • 现有numberOne集合只有4条数据,无法输出你需要的5条结果(ID1434对应paul和john两条),需要调整数据生成逻辑

修复方案

第一步:修正类与测试数据写法

// 类定义保持不变即可
class numberOne 
{
    public long ID {get; set;}
    public string Name {get; set;}
    public string Names {get; set;}
}
class numberTwo
{
    public long[] ID {get; set;}
    public string Name {get; set;}
}

修正后的测试数据初始化:

List<numberOne> numberOneSource = new List<numberOne>
{
    new numberOne() { ID = 1234 },
    new numberOne() { ID = 1334 },
    new numberOne() { ID = 1434 },
    new numberOne() { ID = 1568 }
};
List<numberTwo> numberTwoSource = new List<numberTwo>
{
    new numberTwo() { ID = new long[] {1234,1334}, Name = "sam" },         
    new numberTwo() { ID = new long[] {1434}, Name = "paul" },
    new numberTwo() { ID = new long[] {1434}, Name = "john" },
    new numberTwo() { ID = new long[] {1568}, Name = "john" }
};

第二步:核心逻辑实现

通过双集合关联展开,生成符合要求的结果集:

var result = from two in numberTwoSource
             from id in two.ID
             join one in numberOneSource on id equals one.ID
             select new numberOne
             {
                 ID = id,
                 Name = two.Name,
                 // 拼接当前ID对应的所有去重姓名
                 Names = string.Join(", ", numberTwoSource.Where(t => t.ID.Contains(id)).Select(t => t.Name).Distinct())
             };

第三步:输出结果

// 输出表头
Console.WriteLine("ID  | Name | Names");
// 遍历输出内容
foreach (var item in result)
{
    Console.WriteLine($"{item.ID,-4}|{item.Name,-5}|{item.Names}");
}

运行后即可得到你要求的输出格式:

ID  | Name | Names
1234|sam   |sam
1334|sam   |sam
1434|paul  |paul, john
1434|john  |paul, john
1568|john  |john

内容的提问来源于stack exchange,提问作者darksaky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 23:54:00