Alice
Alice

Reputation: 183

How to use flags to check if something from the collection matches the flag

I'm trying to use flags to filter collection and retrive certain objects.

Perhaps the example will show the issue.

I defined a class and an enum.

    public class ExampleFlagsDto
{
    public int FlagId { get; set; }
    public string Name { get; set; }

}


[Flags]
public enum FlagsTypes
{
    None = 0,
    Small = 1 << 0 ,
    Medium = 1 << 1 ,
    Normal = 1 << 2,
    Large = 1 << 3,
    LargeAndNormal = Normal | Large,
    All = Normal | Medium | Small | Large,

}

Then I constructed a list as an example and tried to retrive 2 objects from the list.

   var examples = new List<ExampleFlagsDto>()
        {
            new ExampleFlagsDto
            {
                FlagId  = (int)FlagsTypes.Normal,
                Name = "First"
            },
            new ExampleFlagsDto
            {
                FlagId  = (int)FlagsTypes.Medium,
                Name = "Second"
            },
            new ExampleFlagsDto
            {
                FlagId  = (int)FlagsTypes.Large,
                Name = "Third"
            },
            new ExampleFlagsDto
            {
                FlagId  = (int)FlagsTypes.Small,
                Name = "Forth"
            },
        };

        var selected = examples.Where(C => C.FlagId == (int)FlagsTypes.LargeAndNormal).ToList();


        foreach (var flag in selected)
        {
            Console.WriteLine(flag.Name);
        }

Of course, it doesn't work. I know that when it comes to bits, (int)FlagTypes.LargeAndNormal would result in a sum of bits of Large and Normal. I have no idea how it has to look like bitwise, though.

I'm looking for a way to change the

  examples.Where(C => C.FlagId == (int)FlagsTypes.LargeAndNormal).ToList();

to a solution that would result in selected having 2 objects from examples.

Upvotes: 1

Views: 386

Answers (1)

michael_c_p
michael_c_p

Reputation: 82

You could try this solution:

var selectedAll = examples.Where(C => (C.FlagId & (int)FlagsTypes.All) == (int)C.FlagId).ToList();

Upvotes: 1

Related Questions