Dynamic Expression using LINQ. How To Find the Kitchens?

前端 未结 5 1821
难免孤独
难免孤独 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:11

    I wouldn't build the where clause in that way - I think it's more complex than it needs to be for your needs. Instead, you can combine where clauses like this:

    var houses = new List(new House[] { myHouse, yourHouse, donaldsHouse });
    
    // A basic predicate which always returns true:
    Func housePredicate = h => 1 == 1;
    
    // A room name which you got from user input:
    string userEnteredName = "a Room";
    
    // Add the room name predicate if appropriate:
    if (!string.IsNullOrWhiteSpace(userEnteredName))
    {
        housePredicate += h => h.MainRoom.Name == userEnteredName;
    }
    
    // A room type which you got from user input:
    RoomType? userSelectedRoomType = RoomType.Kitchen;
    
    // Add the room type predicate if appropriate:
    if (userSelectedRoomType.HasValue)
    {
        housePredicate += h => h.MainRoom.Type == userSelectedRoomType.Value;
    }
    
    // MainRoom.Name = \"a Room\" and Rooms.Count = 3 or 
    // ?????????????????????????
    var aRoomsHouses = houses.AsQueryable().Where(housePredicate);
    

    I tested this one, honest :)

提交回复
热议问题