无法按索引</t>访问IQueryable <t>的项目

时间:2013-06-24 00:24:25

标签: c# iqueryable

我是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++;
                }
            }
        }
    }

我虽然坚持这个错误:

Cannot apply indexing with [] to an expression of type 'System.Linq.IQueryable<Data.Accessory>'

我已经尝试将其转换为字符串列表但由于原因我不明白为什么它不允许我通过索引访问IQueryable

2 个答案:

答案 0 :(得分:1)

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

cell.Text = AccessoryItems[ai];

cell.Text = AccessoryItems.ElementAt(ai) as String;

答案 1 :(得分: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;

它有效!