Dynamic Expression using LINQ. How To Find the Kitchens?

前端 未结 5 1853
难免孤独
难免孤独 2021-01-04 23:29

I try do implement a user dynamic filter, where used selects some properties, selects some operators and selects also the values.

As I didn\'t find yet an answer to

5条回答
  •  误落风尘
    2021-01-05 00:28

    var kitchens = from h in houses
                   where h.MainRoom.Type == RoomType.Kitchen
                   select h;
    

    But you must set the RoomType property on the rooms before.

    Ok, edit:

    so you must redefine:

    var comparison = Expression.Lambda>(...
    

    Then, when you use it:

    var kitchens = houses.AsQueryable().Where(comparison.Compile());
    

    Edit #2:

    Ok, here you go:

    var roomTypeParam = Expression.Parameter(typeof(RoomType), "roomType");
    
    
    
    // ???????????????????????? DOES NOT WORK
    var comparison = Expression.Lambda>(
        Expression.Equal(houseMainRoomTypeParam,
        Expression.Constant(Enum.Parse(typeof(RoomType), "Kitchen"), typeof(RoomType))), houseParam);
    
    
    
    // ???????????????????????? DOES NOT WORK
    var kitchens = houses.AsQueryable().Where(comparison);
    

    Edit #3: Of, for your needs, I am out of ideas for now. I give you one last one:

    Declare an extension method on the String type:

    internal static object Prepare(this string value, Type type)
    {
        if (type.IsEnum)
            return Enum.Parse(type, value);
    
        return value;
    }
    

    Then use it in that expression like:

    Expression.Constant("Kitchen".Prepare(typeof(RoomType)), typeof(RoomType))
    

    That's because apparently enums are treated differently. That extension will leave the string unaltered for other types. Drawback: you have to add another typeof() there.

提交回复
热议问题