5

Given the following enum

[Flags]
public enum Trans{
Purchase =1,
Sale=2,
All  = Purchase | Sale
};

And the following class

public class Person
{
public string Name;
public Trans TransType;
}

And the following data structure

var people = new List<Person>();
people.Add(new Person {Name="James", TransType = Trans.Purchase});
people.Add(new Person {Name="Nancy", TransType = Trans.Sale});
people.Add(new Person {Name="Heather", TransType = Trans.All});
people.Add(new Person {Name="Duane", TransType = Trans.All});

I am trying to query the list for people meeting certain conditions.

To get all people with Trans.Purchase (James, Heather & Duane)

var query = from p in people where ( (p.TransType & Trans.Purchase) == Trans.Purchase) select p;

To get all people with Trans.Sale (Nancy, Heather & Duane)

var query = from p in people where ( (p.TransType & Trans.Sale) == Trans.Sale) select p;

What do I need to specify in the where clause of the LINQ query to return everyone with either Trans.Purchase, Trans.Sale or both (i.e. Trans.All)? (James. Nancy, Heather & Duane)

EDIT Some context - the TransType is stored in a database and am trying to write a screen where the user specified the TransType and a SQL query pulls up the data as specified above

1 Answer 1

11

You could use this query:

var query = from p in people 
            where (p.TransType.HasFlag(Trans.Purchase) || p.TransType.HasFlag(Trans.Sale)) 
            select p;

The query could also be written this way:

var query = from p in people 
            where ((p.TransType & Trans.All) > 0) 
            select p;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That works, but can it be done without using the HasFlag property?
Good sir, many many thanks! Been pulling out my hair for over an hour

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.