在obj数组中选择两个属性

时间:2017-04-29 11:23:28

标签: c# linq select

我已经构建了一个Invoice对象数组,其中包含Quantity,Price,PartDescription和PartNumber属性:

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(并按数量排序)时,我无法获得正确的语法。

我试过

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查询减少原始数组只有两个属性?

1 个答案:

答案 0 :(得分:1)

您应该创建anonymous object

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