我有一個名為 Foo 的類,它有一個 float 和 Bar 屬性。
public class Bar
{
//Contains Stuff
}
public class Foo
{
public Foo(Bar _key, float _score)
{
Bar = _key;
Score = _score;
}
public Bar Key;
public float Score;
}
Bar[] barArray = new Bar[10];
List<Foo> fooList = barArray.ToList() //Where this would initialize the List with 10 Foo elements
// each with the respective Bar object from the array and
//a value of 0.0 for their Score;
我有一組 Bar 物件。我想創建一個 Foo 物件串列,其“Key”屬性初始化為陣列中的值,其“Score”值初始化為 0。
uj5u.com熱心網友回復:
您不能通過呼叫 barArray.ToList() 創建 Foo 串列,因為 Bar 和 Foo 是不同的類,即您不能將 Bar 轉換為 Foo。
如果我對您的理解正確,則此 LINQ 陳述句可能會執行您想要的操作:
List<Foo> fooList = barArray.Select(x => new Foo(x, 0.0)).ToList();
基本上,對于 barArray 中的每個元素,選擇它但創建一個 Foo 物件的新實體,在建構式中傳遞 x 和 0.0,其中 x 是 barArray 中的當前元素并且分數為 0.0,然后將其轉換為一個串列,這本質上回傳一個 Foo 串列。您需要using System.Linq在代碼檔案的頂部添加。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/463218.html
上一篇:SQL到LinqLambda
下一篇:如何將值放入串列型別欄位
