仅返回对象的一些属性

时间:2013-03-29 03:54:10

标签: c#

如果我有一个对象列表,比方说,10个属性,我想返回这些对象的列表,但只有10个属性可用,我该怎么做?

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.

3 个答案:

答案 0 :(得分:5)

您可以使用Select方法使用LINQ并返回anonymous type

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

或者,显式定义您自己的具有3个属性的类,如果您从Domain Entity转换为View Model或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));

答案 1 :(得分: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;}
}

答案 2 :(得分: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.
    });

注意导致enumerable不是Example类型,而是预编译(非运行时)创建的匿名类型。