使用索引从列表中分配对象

时间:2013-10-16 09:51:32

标签: c# .net

如果我有像

这样的作者对象列表
List<Author> authors = new List<Author>{ 
       new  Author { Id = 1, Name = "John Freeman"};
       new  Author { Id = 1, Name = "Adam Kurtz"};
};

这个例子实际上是用静态方法包装的,它返回作者列表。

在我的其他对象中,有Authors类型的属性List<Author>。 现在我想将列表中的第二位作者分配给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>
};

3 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要一个List<Author>,其中包含一位作者。然后在单个ToList()对象上使用Author无效语法。

试试这个:Authors = new List<Author>() { GetAuthors()[1] };

答案 1 :(得分:0)

您无法将单个作者分配到list<Author>,因此您必须创建一个列表(单个作者)来分配它。

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

我不知道,为什么你想根据索引进行采取,理想情况下你应该根据作者的ID编写一个查询来获取价值,以便将来不会产生任何问题。

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

答案 2 :(得分:0)

使用LINQ的解决方案 GetAuthors().Skip(1).Take(1)

编辑:忽略这一切。你正在使用列表。 您实际需要的是使用GetRange

GetAuthors().GetRange(1,1);

相关问题