Ischade
Ischade

Reputation: 126

Unable to access items of an IQueryable<T> by index

I'm new to c#. I'm attempting to use what ought be a list(?) produced by a linq query to build a table on an ordering form. Part of that involves referencing a specific item in that list as below:

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

I'm stuck with this error though:

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

I've tried converting it to a list of strings but for reasons I do not understand why it won't let me access the IQueryable by index.

Upvotes: 3

Views: 7655

Answers (2)

Brad
Brad

Reputation: 639

You could use ElementAt to access an element at a specific point in a sequence. So, replace:

cell.Text = AccessoryItems[ai];

with

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

Upvotes: 2

Ischade
Ischade

Reputation: 126

Figured it out:

                    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();

And this in the for loop:

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

And it works!

Upvotes: 0

Related Questions