Get ordinal position when creating selected item in LINQ expression

How can I get the ordinal position when creating the selected elements in a LINQ expression? For instance:

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 Cars list:

 Car 27 A Car 28 B Car 31 C Car 48 D 

and etc.

+6
source share
1 answer

Use Select overload, which provides an index as well as a value. In this case, I would use AsEnumerable to get out of the database context, and that doesn't mean you want to do 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 code changes, by the way.)

+12
source

Source: https://habr.com/ru/post/894127/


All Articles