tags:

views:

42

answers:

2

I have the following query that runs successfully in LinqPad:

    var results = 
    from container in Container
    join containerType in ContainerType on container.ContainerType equals containerType
    where containerType.ContainerTypeID == 2
    select new { ContainerID = container.ContainerID, TypeID = container.ContainerTypeID};

results.Dump();

I would like to change the select to use an indexer so that the select would look something like this:

select new { ContainerID = container.ContainerID, TypeID = container.ContainerTypeID, ContainerIndex = index  };

What I cannot seem to get right is the proper syntax for select to use the select indexer.

Thanks for your help.

+2  A: 

You can't get the index with the query expression format, but there's an overload for Select that you can use in dot notation that will do it. You can stick to query expression format for the bulk of it, and then add the index in an extra select projection:

var tmp = 
    from container in Container
    join containerType in ContainerType
      on container.ContainerType equals containerType
    where containerType.ContainerTypeID == 2
    select new { ContainerID = container.ContainerID,
                 TypeID = container.ContainerTypeID};

var results = tmp.Select((x, index) => new { x.ContainerID, x.TypeID, 
                                             ContainerIndex = index });
Jon Skeet
@Jon - I should have asked the question 30 minutes, when I started trying to figure this out. Would have saved myself 30 minutes. Thank you.
Randy Minder
Note that the index may not be well defined if you query a database unless you explicitly sort the result because the relational algebra is set-based and does not guarantee any ordering. Usually you get consistent results because the DBMS retrieves the rows by scanning an index or the table but this might change at any point if the optimizer decides that another access path or query plan is more optimal.
Daniel Brückner
+1  A: 

I'm probably missing something, but if your items in Container already have property ContainerTypeID, I don't understand why you need the join. It appears to me that joining to ContainerType is not providing any extra properties that are required for this operation.

As such:

Container
    .Where(c => c.ContainerTypeID==2)
    .Select((c,i) => new {c.ContainerID, c.TypeID, Index = i})
spender
Yeah, I didn't look at the join particularly - I just focused on the indexer bit :)
Jon Skeet
@spender - This is an abbreviated version of my query. I really wanted to understand how to use the indexer in Select given my query. Thank you though.
Randy Minder