3

我是 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<Data.Accessory>”类型的表达式

我尝试将其转换为字符串列表,但由于我不明白为什么它不允许我访问IQueryableby 索引的原因。

4

2 回答 2

2

您可以使用ElementAt访问序列中特定点的元素。所以,替换:

cell.Text = AccessoryItems[ai];

cell.Text = AccessoryItems.ElementAt(ai) as String;
于 2013-06-24T01:43:49.050 回答
0

弄清楚了:

                    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<Accessory> AIL = AccessoryItems.ToList();

这在for循环中:

cell.Text = (string) AIL[ai].AccessoryDescription;

它有效!

于 2013-06-24T19:09:58.580 回答