简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM