Sergio Prats
Sergio Prats

Reputation: 1213

Create a List with the same type that a class property

I want to create a list taking all the values that a property has in a list of certain class and add these values into another list whose type is the same than the class property.

Lets suppose I have the Book class:

public class Book{
    public int code;
    public string genre;
    public string author;
    public string synopsis;
}

Then, I have some method with a List<Book> myList containing some books and I want to populate a list of bookCodes which should be of the same type than Book's property code. I want not to change the declaration of the list of BookCodes List<int> myBookCodes if some day the code property is changed from int to long or Guid, for example.

I have tried things such as

var myBookCodes = new List<typeof(Books.code)>

But I get a "Type expected" error.

I have also tried to use reflection but I also got errors:

System.Reflection.PropertyInfo bookCodeProperty = typeof(Book).GetProperty("code");
Type bookCodeType = bookCodeProperty.PropertyType;

var myBookCodes = new List <>(bookCodeType)

But in this case the compiler complains "bookCodeType is a variable but it is used like a type".

Is there a way to do this?

Upvotes: 4

Views: 600

Answers (1)

Jamiec
Jamiec

Reputation: 136174

This is easy... you just project the list and the type is taken care of for you:

List<Book> myList ...
var codesList = myList.Select(b => b.code).ToList();

if some day the code property is changed from int to long or Guid

Then the code still works, and is now the new type.

Upvotes: 9

Related Questions