簡體   English   中英

使用索引從列表中分配對象

[英]assign object from the list using its index

如果我有Author對象的列表,例如

List<Author> authors = new List<Author>{ 
       new  Author { Id = 1, Name = "John Freeman"};
       new  Author { Id = 1, Name = "Adam Kurtz"};
};

此示例實際上包裝在返回作者列表的靜態方法中。

在我的另一個對象中,有類型為List<Author>屬性Authors 現在,我想將列表中的第二位作者分配給Authors屬性。

我以為我可以使用Authors = GetAuthors()[1].ToList() ; 但是我無法在索引指定的作者上訪問ToList()。

澄清

private static List<Author> GetAuthors() return list of authors (example above). 
var someObject = new SomeObject()
{
   Authors = // select only Adam Kurtz author using index 
             // and assign to Authors property of type List<Author>
};

如果我對您的理解正確,那么您需要其中包含一個作者的List<Author> 因此,在單個Author對象上使用ToList()是無效的語法。

試試這個: Authors = new List<Author>() { GetAuthors()[1] };

您不能將單個作者分配給list<Author> ,因此您必須創建一個(單個作者的)列表來分配它。

Authors = new List<Author>() {GetAuthor()[1]};

我不知道,為什么要基於索引,理想情況下應該基於作者的ID編寫查詢以獲取價值,這樣將來就不會產生任何問題。

像: Authors = new List<Author>() {GetAuthor().FirstOrDefault(x=>x.ID==2)};

LINQ的解決方案是GetAuthors().Skip(1).Take(1)

編輯:忽略所有。 您正在使用列表。 真正需要的是使用GetRange

GetAuthors().GetRange(1,1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM