【发布时间】:2023-03-05 10:01:01
【问题描述】:
我是 C# 新手。我正在尝试使用由 linq 查询生成的应该是列表(?)来在订购表格上构建表。其中一部分涉及引用该列表中的特定项目,如下所示:
using (CellOrderingDBEntities db = new CellOrderingDBEntities())
{
var AccessoryItems = from AccessoryDescription in db.Accessories
join HardwareID in db.HardwareTypes
on AccessoryDescription.HardwareType equals HardwareID.HardwareID
where AccessoryDescription.DateRetired == null
select AccessoryDescription;
List<Device> DevicesList = (List<Device>)Session["DevicesList"];
Guid AccessoriesOrder = (from ServiceID in db.TypeOfServices
where ServiceID.ServiceType == "Accessories Order"
select ServiceID.ServiceID).FirstOrDefault();
//This Int is used to build the accessories table
int AccessoryRows = AccessoryItems.Count();
if (SType == AccessoriesOrder)
{
for (int r = 0; r <= AccessoryRows; r++)
{
TableRow row = new TableRow();
for (int c = 0; c < 3; c++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
int ai = 0;
int ri = 0;
tb.ID = "TextBoxRow_" + r + "Col_" + c;
if (c == 0)
{
cell.Controls.Add(tb);
}
else if (c == 1)
{
cell.Text = AccessoryItems[ai];
ai++;
}
}
}
}
我被这个错误困住了:
无法使用 [] 将索引应用于“System.Linq.IQueryable我尝试将其转换为字符串列表,但由于我不明白为什么它不允许我按索引访问 IQueryable 的原因。
【问题讨论】:
-
如果有人知道一个很好的资源来让我了解类型,我想这就是我没有得到的,因为我一直在努力解决这个问题,我会接受的。非常感谢!
-
你可能会发现使用这个语法更容易:
foreach (var ai in AccessoryItems)而不是这个:for (int r = 0; r <= AccessoryRows; r++),如果你不需要r来索引AccessoryItems以外的任何东西 -
就良好的 LINQ 资源而言:下载 LINQPad (linqpad.net) 并使用它。 (我也可以推荐 J. & B. Albahari 的 C# 4.0/5.0 in a Nutshell btw。)此外,我建议您了解本地(参见 IEnumerable
)和解释查询(参见 IQueryable) 和 LINQ 的延迟执行模式。一旦你理解了这些概念,事情就会变得更加清晰。 -
Linq 操作使用延迟执行,因此仅在您请求时才检索项目。通过索引访问一个项目也意味着首先阅读所有以前的项目,如果你不止一次这样做,这当然是非常低效的。如果您首先将项目加载到集合中(即通过将
.ToList()或.ToArray()附加到查询末尾),然后您可以按索引访问您的项目。 -
除了前面提到的 C# 4.0/5.0 in a Nutshell 和 LINQPad 建议之外,我还推荐 C# in Depth。
标签: c# iqueryable