1

I have a class containing a list of enum-values:

class MyClass
{
    List<Category> ListProperty = ...
}

Now I have a list containing elements of MyClass which I want to filter based on their enum-values-list.

Category is marked with Flags to enable binary combination:

enum Category
{
    None = 0x00,
    Basic = 0x1,
    Geometry = 0x2,
    // ...
    Base_Geometry = 0x100
}

The list within MyClass may consist of an arbitrary number of enum-values that might or might not be binarily combined:

var m = new Myclass { 
    ListProperty = new List<Category> { 
        Category.Some_Category | Category.Another_Category, 
        Category.Basic
    }
});
myList.Add(m);

Now to retrieve all elements within myList that contain a given Category I use this:

var cat = Category.Geometry;
var result = myList.Where(x => x.ListProperty.Any(y => (y & cat) == cat));

The problem now arises when cat consist of multiple enum-values. E.g. when cat is equal to Category.Geometry | Category.Base_Geometry I want to select all elements that have either Geometry, Base_Geometry or even both in their ListProperty. In this case result is empty.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111

1 Answers1

0

This condition

var result = myList.Where(x => x.ListProperty.Any(y => (y & cat) == cat));

requires that y contained all flags inside the cat. If you need y to contain any of the flags within cat, compare the result of & to zero:

var result = myList.Where(x => x.ListProperty.Any(y => (y & cat) != 0));

Note: Consider marking your Category enum with [Flags] attribute, and using Enum.HasFlag method to check an overlap (Q&A with the explanation):

// Requires .NET 4 or later
var result = myList.Where(x => x.ListProperty.Any(y => y.HasFlag(cat));
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523