简体   繁体   中英

Return more than one result

I have a bug that I need more than one result from a foreach without creating a new collection in the method. I need to get rid of the foreach however I don`t know what LINQ method to use.

I have tried,

return basket.Items.SelectMany(
    item => item.Id == orderComplimentaryUtilities.Where(o => o.Id));

public static IEnumerable<OrderItem> WhichUtilitiesAreAlreadyInBasket(
    this 
    IEnumerable<OrderComplimentaryUtility.OrderComplimentaryUtility> 
            orderComplimentaryUtilities,
    Order basket)
{
    if (basket == null || orderComplimentaryUtilities == null)
    {
        return Enumerable.Empty<OrderItem>();
    }
    
    foreach (var orderComplimentaryUtility in orderComplimentaryUtilities)
    {
        return basket.Items.Where(item => item.Id == orderComplimentaryUtility.Id);
    }

    return Enumerable.Empty<OrderItem>();
}


It appears that you are looking to join the data from two sequences ( orderComplimentaryUtilities and basket ), and return the data from basket where they match by id .

You can accomplish this with a LINQ join :

public static IEnumerable<OrderItem> WhichUtilitiesAreAlreadyInBasket(
    this IEnumerable<OrderComplimentaryUtility.OrderComplimentaryUtility> orderComplimentaryUtilities, 
    Order basket)
{
    if (basket == null || orderComplimentaryUtilities == null)
    {
        return Enumerable.Empty<OrderItem>();
    }
    
    var items = orderComplimentaryUtilities
                .Join(basket,
                      u => u.ID,
                      b => b.ID,
                      (u, b) => b);

    return items;
}

You can use Contains if you separate out the ids into a collection:

var ids = orderComplimentaryUtility.Select(i => i.id).ToArray();
return basket.Items.Where(item => ids.Contains(item.Id));

If this is all in-memory, you could inline the Select into the Where clause, but that may not work if you're querying a SQL data source that cannot convert the Select into an IN clause.

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