Search code examples
c#listdynamicanonymous-types

Copy List to another List, but excluding certain properties of List type


This seems like it should be easy, but I can't figure out a tidy way to do it.

With the class

class SomeType
{ 
   public int SomeInteger {get;}
   public string SomeString {get;}
   public object SomeObject {get;}
}

Assuming that a list of SomeType is retrieved from somewhere, but then I need to remove the SomeString field from every item in the list. So I iterate over the list, create an anonymous type and add it to the new list.

List<SomeType> list = GetList();

var newList = new List<dynamic>();
list.ForEach(item => newList.Add(new { SomeInteger = item.SomeInteger, SomeObject = item.SomeObject });

Is there a better way of doing this that doesn't require me to create an empty list of type dynamic? I could be wrong, but it feels like it's not the best way to do this.


Solution

  • You can create a list of anonymous types directly, and this will be strongly-typed:

    list.Select(item => new 
                        { 
                            SomeInteger = item.SomeInteger, 
                            SomeObject = item.SomeObject
                        }).ToList();