C# EF Linq bitwise question

前端 未结 2 876
北恋
北恋 2021-02-06 04:01

Ok for example, I am using bitwise like such: Monday = 1, Tuesday = 2, Wednesday = 4, Thursday = 8 etc...

I am using an Entity Framework class of Business.

I am

2条回答
  •  深忆病人
    2021-02-06 04:54

    Use the bitwise and operator & to combine your desired flags with the actual flags in the database and then check for a non-zero result.

            var b1 = new { DaysOfWeek = 3 };
            var b2 = new { DaysOfWeek = 2 };
            var b = new[] { b1, b2 };
            var filter = 1;
    
            var l = b.Where(o => (filter & o.DaysOfWeek) != 0);
            foreach (var x in l)
            {
                Console.WriteLine(x);
            }
    

    If you have an array of filter values simply combined then with an OR | first:

            var filterArray = new []{1, 4};
            var filter = filterArray.Aggregate((x, y) => x | y);
    

提交回复
热议问题