Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bitwise operations in a LINQ query

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

like image 405
Rad Avatar asked Mar 30 '13 19:03

Rad


1 Answers

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;
like image 177
Adam S Avatar answered Dec 30 '22 14:12

Adam S