简体   繁体   中英

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

For each customer make a list of suppliers located in the same country and the same city

You can use this LINQ query:

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. But it's a deferred executed LINQ query, so you can get a performance issue if you later access them multiple times. If desired you can also append a ToList at the end of the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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