how to query against an array

asp.net-core-mvc entity-framework-core

Question

First off let me start by saying that I'm not sure how to title the question, and I apologize for that. If something strikes me or you as clever I'll edit it.

My problem is this:

public IActionResult(string deckList //comma-separated-string of numeric characters which represent id's)
{
var cards = _context.Cards;
var deckListArray = deckList.Split(',');
foreach (var id in deckListArray)
{
int x = Convert.ToInt32(id);
cards = cards.Where(c => c.ID == id);
}

Alright, so I know that querying inside of a loop is frowned upon to say the least because of performance issues, but this IQueryable collection doesn't even populate correctly with this code.

What would be the appropriate query to get all cards with id's found in the array?

1
2
2/5/2017 12:40:14 AM

Accepted Answer

var ids =  decklist.Split( ',' )
    .Select( id => Convert.ToInt32( id ) )
    .ToArray();

var cards = _context.Cards.Where( c => ids.Contains( c.ID ) );
1
2/5/2017 12:59:43 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow