【问题标题】:Get the ordinal position while creating selected Item in a LINQ expression在 LINQ 表达式中创建选定项时获取序号位置
【发布时间】:2011-08-02 16:54:48
【问题描述】:

在 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

等等

【问题讨论】:

  • 顺便说一下,alphaordinals 可以是字符数组而不是字符串数组:string alphaordinals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

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


【解决方案1】:

使用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 更改为字符串,而无需对代码进行任何其他更改。)

【讨论】:

  • .Select((car, index) => 的标准 linq 等价物是什么
  • @Batu:如果“标准 linq”是指“查询表达式”,则没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
相关资源
最近更新 更多