mmmoustache
mmmoustache

Reputation: 2323

Simplest way to check db values against values in an array

I'm looping through the items in my database using C# .NET and I'm attempting to display different data dependant on if a column value matches any of the values in an array. Because my array could potentially have hundreds of values, I'd rather not create hundreds of different IF statements, if possible. Is there a simpler way to achieve this?

Here's some example code, where "Items" is my db data and "Categories" is a column of said data:

var categoryList = new List<int> { 1, 2, 3, 4 };

foreach(var item in Items){
    if(item.Categories.Any(x => @categoryList.Equals(x))){ 
        <p>Yes</p>
    }else{
        <p>No</p>
    }
}

Upvotes: 0

Views: 99

Answers (1)

Abbas
Abbas

Reputation: 14432

The answer I give is based on the answer of this question. I modified the code to your situation.

foreach(var item in Items)
{
    bool hasCategory = categoryList.Any(x => item.Categories.Any(c => c.Id == x)); 
}

or for larger collections (performance-wise):

bool hasCategory = item.Categories.Select(c => c.Id)
                                  .Intersect(categoryList)
                                  .Any(); 

Edit:

At first I thought item.Categories was a collection of IDs or something but then I started doubting. If item.Categories is just a single integer, following code will work:

foreach(var item in Items)
{
    if(categoryList.Any(x => x == item.Categories))
        <p>Yes</p>
    else
        <p>No</p>
}

Upvotes: 1

Related Questions