9

我尝试实现一个用户动态过滤器,其中使用选择一些属性,选择一些运算符并选择值。

由于我还没有找到这个问题的答案,所以我尝试使用 LINQ 表达式。
主要是我需要确定所有主要房间是厨房的房子(任何感觉,我知道)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
//using System.Linq.Dynamic;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Room aRoom = new Room() { Name = "a Room" };
            Room bRoom = new Room() { Name = "b Room" };
            Room cRoom = new Room() { Name = "c Room" };

            House myHouse = new House
            {
                Rooms = new List<Room>(new Room[] { aRoom }),
                MainRoom = aRoom
            };
            House yourHouse = new House()
            {
                Rooms = new List<Room>(new Room[] { bRoom, cRoom }),
                MainRoom = bRoom
            };
            House donaldsHouse = new House()
            {
                Rooms = new List<Room>(new Room[] { aRoom, bRoom, cRoom }),
                MainRoom = aRoom
            };

            var houses = new List<House>(new House[] { myHouse, yourHouse, donaldsHouse });

            //var kitchens = houses.AsQueryable<House>().Where("MainRoom.Type = RoomType.Kitchen");
            //Console.WriteLine("kitchens count = {0}", kitchens.Count());

            var houseParam = Expression.Parameter(typeof(House), "house");
            var houseMainRoomParam = Expression.Property(houseParam, "MainRoom");
            var houseMainRoomTypeParam = Expression.Property(houseMainRoomParam, "Type");

            var roomTypeParam = Expression.Parameter(typeof(RoomType), "roomType");

            var comparison = Expression.Lambda(
                Expression.Equal(houseMainRoomTypeParam,
                Expression.Constant("Kitchen", typeof(RoomType)))
                );

            // ???????????????????????? DOES NOT WORK
            var kitchens = houses.AsQueryable().Where(comparison);

            Console.WriteLine("kitchens count = {0}", kitchens.Count());
            Console.ReadKey();

        }
    }

    public class House
    {
        public string Address { get; set; }
        public double Area { get; set; }
        public Room MainRoom { get; set; }
        public List<Room> Rooms { get; set; }
    }

    public class Room
    {
        public double Area { get; set; }
        public string Name { get; set; }
        public RoomType Type { get; set; }
    }

    public enum RoomType
    {
        Kitchen,
        Bedroom,
        Library,
        Office
    }
}
4

5 回答 5

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

但是您必须先RoomType在房间上设置属性。

好的,编辑:

所以你必须重新定义:

var comparison = Expression.Lambda<Func<House, bool>>(...

然后,当你使用它时:

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

编辑#2:

好的,给你:

var roomTypeParam = Expression.Parameter(typeof(RoomType), "roomType");



// ???????????????????????? DOES NOT WORK
var comparison = Expression.Lambda<Func<House, bool>>(
    Expression.Equal(houseMainRoomTypeParam,
    Expression.Constant(Enum.Parse(typeof(RoomType), "Kitchen"), typeof(RoomType))), houseParam);



// ???????????????????????? DOES NOT WORK
var kitchens = houses.AsQueryable().Where(comparison);

编辑#3:出于您的需要,我现在没有想法。我给你最后一个:

在 String 类型上声明一个扩展方法:

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

    return value;
}

然后在该表达式中使用它,例如:

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

那是因为显然枚举的处理方式不同。该扩展名将使其他类型的字符串保持不变。缺点:你必须在typeof()那里添加另一个。

于 2011-08-16T11:07:37.520 回答
0

我不会以这种方式构建 where 子句 - 我认为它比您需要的更复杂。相反,您可以像这样组合 where 子句:

var houses = new List<House>(new House[] { myHouse, yourHouse, donaldsHouse });

// A basic predicate which always returns true:
Func<House, bool> 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<House>().Where(housePredicate);

我测试了这个,老实说:)

于 2011-08-16T11:14:07.823 回答
0
// ???????????????????????? DOES NOT WORK
var kitchens = houses.AsQueryable().Where(comparison);

Where方法以 aFunc<House, bool>或 aExpression<Func<House, bool>>作为参数,但变量comparison的类型为LambdaExpression,不匹配。您需要使用该方法的另一个重载:

var comparison = Expression.Lambda<Func<House, bool>>(
                Expression.Equal(houseMainRoomTypeParam,
                Expression.Constant("Kitchen", typeof(RoomType))));
//now the type of comparison is Expression<Func<House, bool>>

//the overload in Expression.cs
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters);
于 2011-08-16T11:08:33.673 回答
-1

那这个呢

var kitchens = houses
                .SelectMany(h => h.Rooms, (h, r) => new {House = h, Room = r})
                .Where(hr => hr.Room.Type == RoomType.Kitchen)
                .Select(hr => hr.House);
于 2011-08-16T11:06:43.670 回答
-1

要将新Enum类型添加到动态 Linq,您必须添加以下代码:

typeof(Enum),
typeof(T)

T : Enum type

在预定义的动态类型中。这对我行得通。

于 2013-03-22T13:10:24.153 回答