【问题标题】:select two properties in an array of obj在 obj 数组中选择两个属性
【发布时间】:2017-04-29 19:31:32
【问题描述】:

我已经构建了一个带有属性 Quantity、Price、PartDescription 和 PartNumber 的 Invoice 对象数组:

Invoice[] invoices = {
        new Invoice( 83, "Electric sander", 7, 57.98M ),
        ...
        new Invoice( 3, "Wrench", 34, 7.5M ) }; // end initializer list

我已经成功创建了两个副本,使用查询按 PartDescription 和 Price 排序

IEnumerable<Invoice> invoicesByPartDescription = 
invoices.OrderBy(invoice => invoice.PartDescription);

IEnumerable<Invoice> invoicesByPrice =
invoices.OrderBy(invoice => invoice.Price);

到目前为止,一切都很好。但是,当我尝试制作第三份副本,但选择 PartDescription 和 Quantity(并按 Quantity 排序)时,我无法获得正确的语法。

我试过了

IEnumerable<Invoice> invoicesSelPartDescription = 
invoices.Select(invoice => invoice.PartDescription)
.Select(invoice => invoice.Quantity)
.OrderBy(invoice => invoice.Quantity);

,但是 Visual Studio 抛出关于第二个 Select 的错误,说没有定义 Quantity 方法。

我想要一个数组,在格式化输出时,会给出如下内容:

{ PartDescription = Lawn mower, Quantity = 3 }

所以我想我的问题是:如何使用 Linq 查询将原始数组缩减为只有两个属性?

【问题讨论】:

    标签: c# linq select


    【解决方案1】:

    你应该创建一个anonymous object

    var invoicesSelPartDescription = invoices
        .Select(invoice => new
            {
                invoice.PartDescription,
                invoice.Quantity
            })
        .OrderBy(x => x.Quantity);
    

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多