简体   繁体   English

LINQ-根据集合属性选择匿名类型

[英]LINQ - Select anonymous type which based on a collection property

I have the following Class: 我有以下课程:

public class DistributionItem
{

    public int DeviceID { get; set; }
    public string DeviceName { get; set; }
    public double? Export { get; set; }
    public double? Import { get; set; }
    public List<double?> Tarrifs { get; set; }
    public bool HasChild { get; set; }
    public int OrderNum { get; set; }
    public double PF { get; set; }
    public int? MaxDmd { get; set; }
    public string ImageUrl { get; set; }
    public int ParentID { get; set; }
    public double? Total { get; set; }
}

I want to make a LINQ Select over a List of this class to pull-out some of the properties like this: 我想在该类的列表上进行LINQ Select ,以拉出如下所示的某些属性:

        return data.Select(x => new
        {
            x.DeviceID,
            x.DeviceName,
            x.HasChild,
            x.KwhImport,
            x.KwhExport,
            x.MaxDmd,
            x.ParentID
        }).ToList();

How can I add the Tarrifs values as separate properties to the anonymous object? 如何将Tarrifs值作为单独的属性添加到匿名对象?

You can't, unless you know the number of items in the list at compile time. 除非您在编译时知道列表中的项目数,否则就不能。 The idea of anonymous types is that they're statically typed . 匿名类型的想法是它们是静态类型的 The compiler knows, at compile time, what all of the properties and their types are. 编译器在编译时就知道所有属性及其类型是什么。 You can't use one if you don't know that information. 如果您不知道该信息,则不能使用。

If you know that there are, for example, always two items, then you can do something like: 例如,如果您知道总是有两个项目,则可以执行以下操作:

return data.Select(x => new
{
    x.DeviceID,
    x.DeviceName,
    x.HasChild,
    x.KwhImport,
    x.KwhExport,
    x.MaxDmd,
    x.ParentID,
    Tarrifs1 = x.Tarrifs[0],
    Tarrifs2 = x.Tarrifs[1],
}).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM