简体   繁体   English

如何使用 enumerable 和 model 返回 enumerable?

[英]How to return enumerable with enumerable and with model?

I can't figure out how to cast to the type to be returned.我不知道如何转换为要返回的类型。 In this example, there must be a certain condition, but I think I can handle it.在这个例子中,必须有一定的条件,但我认为我可以处理它。 The main thing for me is to understand how to return it.对我来说最主要的是了解如何退货。 The task itself looks like this, but the priority is to understand how to work with such returns (For each customer make a list of suppliers located in the same country and the same city)任务本身看起来像这样,但首要任务是了解如何处理此类退货(为每个客户列出位于同一国家和同一城市的供应商)

       public static IEnumerable<(Customer customer, IEnumerable<Supplier> suppliers)> Linq2(
            IEnumerable<Customer> customers,
            IEnumerable<Supplier> suppliers
        )
        {
            var q2 = from customer in customers
                select new Collection() { customer, suppliers };
            return q2;
        }

I tried this but an error occurs with an anonymous type.我试过这个但是匿名类型发生错误。

I tried returning with linq but but got an error due to anonymous type我尝试使用 linq 返回,但由于匿名类型而出现错误

For each customer make a list of suppliers located in the same country and the same city为每个客户列出位于同一国家和同一城市的供应商名单

You can use this LINQ query:您可以使用此 LINQ 查询:

return customers
    .Select(c => (customer:c, suppliers:suppliers
        .Where(s => s.Country == c.Country && s.City == c.City)
        .ToList()));

The ToList is not necessary, you have already an IEnumerable<Supplier> without. ToList不是必需的,您已经有一个IEnumerable<Supplier>没有。 But it's a deferred executed LINQ query, so you can get a performance issue if you later access them multiple times.但它是一个延迟执行的 LINQ 查询,因此如果您稍后多次访问它们,您可能会遇到性能问题。 If desired you can also append a ToList at the end of the query.如果需要,您还可以在查询末尾使用 append ToList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM