2

如何使用扩展方法制作这个表达式,但(!)不使用匿名类型?

from p in posts
               join u in context.oxite_Users on p.CreatorUserID equals u.UserID
               join pa in context.oxite_PostAreaRelationships on p.PostID equals pa.PostID
               join a in context.oxite_Areas on pa.AreaID equals a.AreaID
               let c = getCommentsQuery(p.PostID)
               let t = getTagsQuery(p.PostID)
               let tb = getTrackbacksQuery(p.PostID)
               let f = getFilesQuery(p.PostID)
               where p.State != (byte)EntityState.Removed
               orderby p.PublishedDate descending
               select new Post
               { area = a, comments = c } e.t.c.
4

1 回答 1

2

这里的关键是引入一个元组,它封装了join操作和其他lets的组合状态。我不能仅以此为基础复制您的环境,但这是一个有限的示例,应该清楚(ish);

using System.Linq;
static class Program
{
    static void Main()
    {
        var users = new User[0]; // intentionally 0; only exists to prove compiles
        var orders = new Order[0];

        var query = users.Join(orders, user => user.UserId, order => order.OrderId, (user,order) => new UserOrderTuple(user,order))
            .Where(tuple => tuple.State != 42).OrderByDescending(tuple => tuple.Order.OrderId)
            .Select(tuple => new ResultTuple { Comment = tuple.Comment });
    }
}

class ResultTuple
{
    public string Comment { get; set; }
}
class UserOrderTuple
{
    public UserOrderTuple(User user, Order order)
    {
        User = user;
        Order = order;
        Comment = "some magic that gets your comment and other let";
        State = 124;
    }
    public string Comment { get; private set; }
    public int State { get; private set; }
    public User User { get; private set; }
    public Order Order { get; private set; }
}
class User
{
    public int UserId { get; set; }
}
class Order
{
    public int UserId { get; set; }
    public int OrderId { get; set; }
}
于 2010-08-25T11:13:27.673 回答