C# 如何将LINQ查询与IQueryable

C# 如何将LINQ查询与IQueryable,c#,linq-to-sql,C#,Linq To Sql,我有一个LINQ查询,它使用1个表+大量视图。我希望能够写出这样的东西: IQueryable<Guid> mostViewedWriters; switch (datePicker) { case DatePicker.Last12Hours: mostViewedWriters = from x in context.tempMostViewed12Hours select x.GuidId;

我有一个LINQ查询,它使用1个表+大量视图。我希望能够写出这样的东西:

IQueryable<Guid> mostViewedWriters;

switch (datePicker)
{
    case DatePicker.Last12Hours:
        mostViewedWriters = from x in context.tempMostViewed12Hours
                            select x.GuidId;
        break;
    case DatePicker.Last24Hours:
        mostViewedWriters = from x in context.tempMostViewed24Hours
                            select x.GuidId;
        break;
    case DatePicker.Last36Hours:
        mostViewedWriters = from x in context.tempMostViewed36Hours
                            select x.GuidId;
        break;
}

var query = from x1 in context.Articles
join x2 in context.Authors on x1.AuthorId == x2.AuthorId
join x3 in mostViewedWriters on x2.AuthorId == x3.Id
select new { x2.AuthorName, x1.ArticleId, x1.ArticleTitle };
var query = from article in context.Articles
            join author in context.Authors on article.AuthorId == author.AuthorId
            join id in mostViewedWriters on author.AuthorId == id
            select new { x2.AuthorName, x1.ArticleId, x1.ArticleTitle };
上面的C是为保护无辜的我而编写的伪代码。问题的要点是:我有一个与视图结果相关的查询。然而,这种观点可能是许多不同观点中的一种。所有视图都返回相同的数据类型。我想我可能能够创建一个IQueryable,其中包含我需要的ID并使用该查询。遗憾的是,这项工作已经停滞。

您的问题是,大多数ViewedWriter没有命名字段,因为它只是一个返回Guid列表的集合/查询,所以您应该像这样重写查询:

IQueryable<Guid> mostViewedWriters;

switch (datePicker)
{
    case DatePicker.Last12Hours:
        mostViewedWriters = from x in context.tempMostViewed12Hours
                            select x.GuidId;
        break;
    case DatePicker.Last24Hours:
        mostViewedWriters = from x in context.tempMostViewed24Hours
                            select x.GuidId;
        break;
    case DatePicker.Last36Hours:
        mostViewedWriters = from x in context.tempMostViewed36Hours
                            select x.GuidId;
        break;
}

var query = from x1 in context.Articles
join x2 in context.Authors on x1.AuthorId == x2.AuthorId
join x3 in mostViewedWriters on x2.AuthorId == x3.Id
select new { x2.AuthorName, x1.ArticleId, x1.ArticleTitle };
var query = from article in context.Articles
            join author in context.Authors on article.AuthorId == author.AuthorId
            join id in mostViewedWriters on author.AuthorId == id
            select new { x2.AuthorName, x1.ArticleId, x1.ArticleTitle };

第二个连接条件直接连接行中的值,因为它只是一个Guid。我还更改了变量名称,以使其更清晰一些原则上,我认为您所描述的应该可以工作,尽管可能存在许多技术问题。如果您尝试编译并运行示例,您会得到什么?我认为您的意思是在伪代码中使用不同的视图名称,例如context.tempMostViewed36Hours。不?鲁法马蒂,你说得对。谢谢。汤姆斯,我甚至不能让那些小家伙离开。编写时,x2.Id将生成一个错误,因为大多数ViewedWriter没有任何命名字段。这正是我要查找的。谢谢