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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With