在LINQ表达式中创建所选项时获取序号位置

时间:2011-08-02 16:54:48

标签: c# linq linq-to-sql ordinals

如何在LINQ表达式中创建所选项目时获取序号位置?例如:

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

我希望汽车列表的 InventoryItem.UIElement 如下:

Car 27 A

Car 28 B

Car 31 C

Car 48 D

1 个答案:

答案 0 :(得分:13)

使用提供索引和值的Select重载。在这种情况下,我会使用AsEnumerable退出数据库上下文,这实际上并不是你想要做这项工作的地方:

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

(您可以将alphaOrdinals更改为字符串,而无需对代码进行任何其他更改,顺便说一句。)