使用对象的索引从列表中分配对象
本文关键字:对象 列表 分配 索引 | 更新日期: 2023-09-27 18:35:39
如果我有作者对象列表,例如
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);