Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a List with the same type that a class property

Tags:

c#

list

generics

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?

like image 203
Sergio Prats Avatar asked Jan 02 '23 20:01

Sergio Prats


1 Answers

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.

like image 135
Jamiec Avatar answered Jan 04 '23 10:01

Jamiec