Search code examples
c#genericsprojection

Projection to select elements from List<T>


I have a class

public class MyClass
{
  public p1 {get; set}
  public p2 {get;set;}
  public p3 {get;set;}
}

and a generic list List<MyClass> myList.

I know that I can write

var myvar = from x in myList select new {x.p1, x.p2};

How do I write a projection to select only p1 and p2 from MyList using extension Select method?

myList.Select(????

Documentation Enumerable.Select only shows how to select single value

IEnumerable<int> squares =
    Enumerable.Range(1, 10).Select(x => x * x);

Solution

  • Pretty straightforward

    myList.Select(elem => new { elem.p1, elem.p2 });