David
David

Reputation: 1611

Make a List of objects using an existing list

I have a class named DataAPIKey. I have a second class which inherits from that one.

In my code I have a List, and I would like to use that to make a list of the new class. Is there any way to do this without using a for each loop?

Using the example below I made the following code which seems to be doing what I want.

List<DataAPIKey> apiList = db.GetPendingAction("Character");

List<DataCharacter> charList = apiList.Select(k => {
        DataCharacter dc = new DataCharacter(k.apiKeyId, k.keyId, k.verificationCode);
        return dc;
    }).ToList()

Upvotes: 0

Views: 52

Answers (1)

Trevor Elliott
Trevor Elliott

Reputation: 11252

Use the LINQ Select method.

var newList = oldList.Select(oldItem => new InheritedItem(oldItem)).ToList();

In plain English this translates to "Take each item from oldList, feed each as a function parameter to a function which will take that item and perform some logic to return a different type of item, then take all the returned items and populate them into a new List."

Or if you don't have a constructor to initialize the inherited class then you can provide any code block:

var newList = oldList.Select(oldItem =>
{
    var newItem = new InheritedItem();
    newItem.Property = oldItem.Property;
    return newItem;
}).ToList();

Or an initializer:

var newList = oldList.Select(oldItem => new InheritedItem()
{
    Property = oldItem.Property,
    Property2 = oldItem.Property2
}).ToList();

Upvotes: 6

Related Questions