C# EF Linq bitwise question

﹥>﹥吖頭↗ 提交于 2019-12-03 14:14:34

问题


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 using a class and passing in a value like 7 (Monday, Tuesday, Wednesday).

I want to return records that match any of those days

    public List<Business> GetBusinesses(long daysOfWeek)
    {
         using (var c = Context())
         {
              return c.Businesses.Where(???).ToList();
         }
    }

Any help would be appreciated. Thanks!

EDIT

Ok, so I am attempting the following:

var b = new List<Business>();
var b1 = new Business(){DaysOfWeek = 3};
b.Add(b1);
var b2 = new Business() { DaysOfWeek = 2 };
b.Add(b2);
var decomposedList = new[]{1};
var l = b.Where(o => decomposedList.Any(day => day == o.DaysOfWeek)).ToList(); 

But l returns 0 results assuming in the decomposedList(1) I am looking for monday. I created b1 to contain Monday and Tuesday.


回答1:


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);



回答2:


You must decompose the long value(bitflagged enum will be better) to it's parts then pass it to Where

return c.Businesses.Where(o=> DecomposeDays(dayParam).Any(day => day==o)).ToList();

EDIT: decompose method:

private static IEnumerable<byte> DecomposeDays(byte dayParam)
{
    var daysOfWeek = new List<byte> { 1, 2, 4, 6, 8 ,16};
    return daysOfWeek.Where(o => (o & dayParam) == dayParam);
}


来源:https://stackoverflow.com/questions/4696169/c-sharp-ef-linq-bitwise-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!