在 C# 中,可以通过使用泛型和 LINQ 查询来实现不同表组合条件的高级查询通用方法。下面是一个示例代码:

using System;
using System.Collections.Generic;
using System.Linq;

public class QueryUtility<T>
{
    private IQueryable<T> query;

    public QueryUtility(IQueryable<T> query)
    {
        this.query = query;
    }

    public QueryUtility<T> Where(Func<T, bool> predicate)
    {
        query = query.Where(predicate);
        return this;
    }

    public QueryUtility<T> Join<U>(IQueryable<U> other, Func<T, U, bool> predicate)
    {
        query = query.Join(other, x => true, y => true, (x, y) => new { x, y }).Where(z => predicate(z.x, z.y)).Select(z => z.x);
        return this;
    }

    public IQueryable<T> Execute()
    {
        return query;
    }
}

使用这个通用查询方法,你可以按照以下方式进行高级查询:

var customers = new List<Customer>
{
    new Customer { Id = 1, Name = 'John' },
    new Customer { Id = 2, Name = 'Alice' },
    new Customer { Id = 3, Name = 'Bob' }
}.AsQueryable();

var orders = new List<Order>
{
    new Order { Id = 1, CustomerId = 1, Product = 'Apple' },
    new Order { Id = 2, CustomerId = 2, Product = 'Banana' },
    new Order { Id = 3, CustomerId = 3, Product = 'Orange' }
}.AsQueryable();

var query = new QueryUtility<Customer>(customers)
    .Join(orders, (customer, order) => customer.Id == order.CustomerId)
    .Where(customer => customer.Name.StartsWith('A'));

var result = query.Execute().ToList();

在上面的示例中,我们定义了两个实体类 Customer 和 Order,然后使用 QueryUtility 类进行高级查询。首先,我们将 customers 和 orders 转换为 Queryable 对象,然后使用 Join 方法将它们连接起来,最后使用 Where 方法添加筛选条件。最后,我们通过调用 Execute 方法来执行查询,并将结果转换为列表。

这种方法可以通用地组合不同表和条件进行高级查询,并且可以根据需要进行扩展和定制。

C# 高级查询通用方法 - 实现不同表组合条件的灵活查询

原文地址: https://www.cveoy.top/t/topic/qBmY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录