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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With