Get the ordinal position while creating selected Item in a LINQ expression
Asked Answered
W

1

7

How can I get the ordinal position while creating selected Items in a LINQ expression? For example:

var alphaordinals = new string[] { "A", "B", "C", "D", "E" };  // etc.
var q = from car in datacontext.Cars
        select new InventoryItem
        {
            Name = car.Name,
            Price = car.Price,
            UIElement = "Car " + car.Id.ToString() + ???                        
        };
return q.ToList();

I want the InventoryItem.UIElement of the list of Cars to be like :

Car 27 A

Car 28 B

Car 31 C

Car 48 D

etc.

Winfordwinfred answered 2/8, 2011 at 16:54 Comment(1)
By the way, alphaordinals could be a character array rather than a string array: string alphaordinals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";Nostoc
L
15

Use the overload of Select which provides the index as well as the value. In this case I'd use AsEnumerable to get out of the database context, which isn't really where you want to be doing this work:

string[] alphaOrdinals = { "A", "B", "C", "D", "E" };
var query = dataContext.Cars
                       .AsEnumerable()
                       .Select((car, index) => new InventoryItem { 
                                  Name = car.Name,
                                  Price = car.Price,
                                  UIElement = string.Format("Car {0} {1}",
                                                            car.Id,
                                                            alphaOrdinals[index])
                               }).ToList();

(You can change alphaOrdinals to a string without any other change to the code, btw.)

Lycanthrope answered 2/8, 2011 at 17:0 Comment(2)
what is the standard linq equivalent of .Select((car, index) =>Rude
@Batu: If by "standard linq" you mean "query expression", there isn't one.Lycanthrope

© 2022 - 2024 — McMap. All rights reserved.