Home > Back-end >  How to return enumerable with enumerable and with model?
How to return enumerable with enumerable and with model?

Time:01-19

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

CodePudding user response:

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.

  • Related