2

I have a list of MyItem objects called myItems like this:

public class MyItem{
    public int[] category_ids;
    public string name;
}

List<MyItem> myItems;

I want to filter down the list of objects with a list of selected categories so that the filtered list contains ANY of the filter category ids:

int[] filter = { 1, 5, 6, 9 };

How would I do that using LINQ in one line? (if its even possible, I cant wrap my head around it!) I imagine something along the lines of:

IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Contains(xxx));

3 Answers 3

2
var filtered = myItems.Where(x => x.category_ids.Intersect(filter)
                                          .Any());
Sign up to request clarification or add additional context in comments.

Comments

2

Needs one more method call:

IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Any(x=>filter.Contains(x));

Comments

2

Another option than the one already presented:

var filtered = myItems.Where( item => item.category_ids.Intersect( filter ).Count() > 0 );

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.