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>();
}
CodePudding user response:
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;
}
CodePudding user response:
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.