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

如何返回包含Customer及对应Supplier枚举集合的IEnumerable类型?

解决LINQ返回值类型不匹配问题

你的核心问题是返回类型和LINQ查询生成的类型不匹配,同时还没实现"筛选同国家同城市供应商"的业务逻辑,下面是修正方案:

错误点分析

  • 你用new Collection()构造的集合类型,和方法声明的值元组类型完全不符,方法要求返回IEnumerable<(Customer, IEnumerable<Supplier>)>,不是普通集合实例
  • 直接传入所有suppliers,没有筛选出和当前客户同国家、同城市的供应商
  • 匿名类型报错是因为你没明确构造方法要求的元组,反而创建了编译器无法识别的匿名对象/错误集合

修正后的代码

查询表达式写法

public static IEnumerable<(Customer customer, IEnumerable<Supplier> suppliers)> Linq2(
    IEnumerable<Customer> customers,
    IEnumerable<Supplier> suppliers
)
{
    var q2 = from customer in customers
             select (
                 customer: customer,
                 suppliers: suppliers.Where(s => s.Country == customer.Country && s.City == customer.City)
             );
    return q2;
}

方法链写法(更简洁)

public static IEnumerable<(Customer customer, IEnumerable<Supplier> suppliers)> Linq2(
    IEnumerable<Customer> customers,
    IEnumerable<Supplier> suppliers
)
{
    return customers.Select(c => (
        customer: c,
        suppliers: suppliers.Where(s => s.Country == c.Country && s.City == c.City)
    ));
}

关键说明

  • 直接构造方法要求的命名值元组,编译器会自动匹配返回类型,不会出现匿名类型报错
  • 用Where筛选出和当前客户Country、City完全一致的供应商,满足业务需求
  • 不需要额外创建Collection或其他容器,LINQ查询直接生成符合要求的IEnumerable<(...)>序列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:40:18