在 IQueryable 中存储多个 linq 查询的结果

Storing results of multiple linq queries in IQueryable

我想知道是否可以将多个 linq 查询的结果存储在单个 IQueryable 语句中?

我有一个在 foreach 中使用的查询:

//Where OnDemandHistory is the table
IOrderedQueryable<OnDemandHistory> A; 

foreach (int id in machineID)
{
    A = OnDemandHistory.Where(c => c.MachineID == id).OrderByDescending(c => c.ODHisDate);
    // I want to Order all results before writing to the table
    foreach(var entry in A)
    {         
      // I add to a table based on all entries found in A
    }
}

我正在尝试获取机器 ID 匹配的所有条目。没有。 MachineID 的数量不同(基于用户)。

我想知道是否可以在存储所有查询结果之后但在添加到 table.

之前执行 OrderByDescending

我知道由于内部 foreach 循环,它不会发生,但是当我尝试这样做时:

foreach (int id in machineID)
{
    A = OnDemandHistory.Where(c => c.MachineID == id).OrderByDescending(c => c.ODHisDate);
    // I want to Order all results before writing to the table       
}

foreach(var entry in A)
{         
    // I add to a table based on all entries found in A
}

我得到一个局部变量A未初始化的错误,

我该如何解决这个问题?

提前致谢

错误是因为您的第一个查询的最终结果仅产生 machineID 的最后一个值的结果,这可能导致 A 的结果为空或未初始化的值,因此 A 需要被初始化。另外,我怀疑 A 可能是一个简单的列表。

你需要这样的东西:

A = new List<OnDemandHistory>();
foreach (int id in machineID)
{
    A.AddRange(OnDemandHistory
     .Where(c => c.MachineID == id).OrderByDescending(c => c.ODHisDate).ToList());          
}
// order A here

然后 运行 你的第二个循环检查了 A 是否有行。但是,我怀疑 LINQ 中有更智能的方法将查询的 machineID 部分连接为单个 LINQ 语句。

您可以使用 Contains 语句来更简单:

var result = OnDemandHistory.Where(c => machineID.Contains(c.MachineID))
                            .OrderByDescending(c => c.ODHisDate);