2

如果我有一个包含 10 个属性的对象列表,并且我想返回这些对象的列表,但 10 个属性中只有 3 个可用,我该怎么做?

public class Example
{
    public int attr1 {get;set;}
    public int attr2 {get;set;}
    public int attr3 {get;set;}
    public int attr4 {get;set;}
    public int attr5 {get;set;}
}

return ExampleList; //have the return value be a list with only attr1, 2, and 3 visible.
4

3 回答 3

7

您可以将 LINQ 与Select方法一起使用并返回匿名类型

var result = ExampleList.Select(x => new { x.attr1, x.attr2, x.attr3 });

或者,使用 3 个属性显式定义您自己的类,如果您从域实体转换为视图模型或 Dto 对象,这种情况很常见:

class Dto
{
    public int Pro1 { get; set; }
    public int Pro2 { get; set; }
    public int Pro3 { get; set; }
}

var result = ExampleList.Select(x => new Dto { 
                                       Pro1 = x.attr1,
                                       Pro2 = x.attr2,
                                       Pro3 = x.attr3 
                                    });

或者,如果您只想要一个转储类,您可以使用Tuple

var result = ExampleList.Select(x => Tuple.Create(x.attr1, x.attr2, x.attr3));
于 2013-03-29T03:56:17.413 回答
0

使属性可以为空并使用Object Initializers

public class Example
{
    public int? attr1 {get;set;}
    public int? attr2 {get;set;}
    public int? attr3 {get;set;}
    public int? attr4 {get;set;}
    public int? attr5 {get;set;}
}
于 2013-03-29T03:57:39.163 回答
0

使用 LINQ 投影运算符:

var resultList = ExampleList.Select(x => new
    {
        x.attr1,
        x.attr2,
        x.attr3
    });

或者,如果您需要指定其他道具名称:

var resultList = ExampleList.Select(x => new
    {
        PropName1 = x.attr1,
        PropName2 = x.attr2,
        PropName2 = x.attr3, // <- The last comma can be leaved here.
    });

Pay attention that resulted enumerable is not of type Example but of pre-compile (not runtime) created anonymous type.

于 2013-03-29T03:58:09.360 回答