0

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>
    }
}

1 Answer 1

1

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>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.