0

我有一个名为 DataAPIKey 的类。我有第二个类,它继承自那个类。

在我的代码中,我有一个列表,我想用它来制作新类的列表。有没有办法在不使用 for each 循环的情况下做到这一点?

使用下面的示例,我制作了以下代码,这似乎正在做我想做的事情。

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()
4

1 回答 1

6

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();
于 2013-10-16T22:52:30.057 回答