Returning only a few properties of an object

c#

Solution

You can use LINQ with `Select` method and return anonymous type:

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

Or, explicitly define your own class with 3 properties, this case is usual if you convert from Domain Entity to View Model or Dto object:

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 
                                    });

Or if you just want a dump class, you can use `Tuple`:

var result = ExampleList.Select(x => Tuple.Create(x.attr1, x.attr2, x.attr3));

Problem

If I've got a list of objects with, let's say, 10 properties, and I want to return a list of these objects but with only 3 properties of the 10 available, how would I do that? ``` 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. ```

Original source