代码之家  ›  专栏  ›  技术社区  ›  John Gietzen

我可以在linqto实体中动态构建where子句吗?

  •  2
  • John Gietzen  · 技术社区  · 14 年前

    我正在尝试为linqto实体动态构建一个LINQ查询,这样就可以避免重复同一个函数两次。

    我想做的是:

    private IUser GetOrUpdateUser(Predicate<IUser> filter, Func<IIdentityProvider, UserRecord> fetch)
    {
        var user = (from u in this.adapter.Users
                    where filter(u)
                    select u).SingleOrDefault();
    
        if (user == null)
        {
            // User not found.  Add him.
            user = this.adapter.AddUser(fetch(this.idenityProvider));
        }
        else if (user.IsExpired)
        {
            // User found, but expired.  Update him.
            this.adapter.UpdateUser(user, fetch(this.idenityProvider));
        }
    
        return user;
    }
    
    protected IUser GetUserByNetworkId(string username)
    {
        return GetOrUpdateUser(
            u => u.NetworkId == username,
            i => i.GetUserByNetworkId(username));
    }
    
    protected IUser GetUserByEmail(string email)
    {
        return GetOrUpdateUser(
            u => u.Email == email,
            i => i.GetUserByEmail(email));
    }
    

    这个 filter

    protected IUser GetUserByNetworkId(string username)
    {
        return GetOrUpdateUser(
            from u in this.adapter.Users
            where u.NetworkId == username
            select u,
            i => i.GetUserByNetworkId(username));
    }
    
    protected IUser GetUserByEmail(string email)
    {
        return GetOrUpdateUser(
            from u in this.adapter.Users
            where u.Email == email
            select u,
            i => i.GetUserByEmail(email));
    }
    

    3 回复  |  直到 14 年前
        1
  •  1
  •   djdd87    14 年前

    您可以将两个LINQ语法组合起来:

    private IQueryable<IUser> BuildQuery(IQueryable<IUser> users, string userName)
    {
        users = users.Where(u => u.UserName == userName);
        return users;
    }
    

    当你称之为:

    var query = from u in this.BuildQuery(this.adapter.Users, userName)
                select u;
    

        2
  •  1
  •   Craig Stuntz    14 年前

    Expression<Func<... ,不仅仅是 Func<...

    Expression<Func<User, Bool>> MakePredicate(int id)
    {
        return u => u.Id == id;
    }
    
    void DoStuff()
    {
        Expression<Func<User, Bool>> pred = MakePredicate(123);
        User u = Context.Users.Where(pred).Single()
    }
    

    User ,不是 IUser (或类似的)。

        3
  •  0
  •   Bhuvan    14 年前

    1. LINQ Expression Builder ,和
    2. LinqPad LinQkit 这是开源的。PredicateBuilder类演示如何动态构建Linq查询表达式。

    为了您的即时使用,我建议使用谓词生成器。