【问题标题】:assign object from the list using its index使用其索引从列表中分配对象
【发布时间】:2013-10-24 09:05:04
【问题描述】:

如果我有像

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

这个例子实际上包含在返回作者列表的静态方法中。

在我的另一个对象内部有List&lt;Author&gt; 类型的属性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>
};

【问题讨论】:

  • 不确定我是否理解您的问题您需要Authors = new List&lt;Author&gt;(){someObject[1]}; 吗?
  • 我只需要实例化 new List() 而不是指定索引指定作者,就像下面回答的那样

标签: c# .net


【解决方案1】:

如果我对您的理解正确,您需要一个 List&lt;Author&gt;,其中包含一个作者。在单个 Author 对象上使用 ToList() 是无效的语法。

试试这个:Authors = new List&lt;Author&gt;() { GetAuthors()[1] };

【讨论】:

    【解决方案2】:

    您不能将单个作者分配给list&lt;Author&gt;,因此您必须创建一个(单个作者的)列表来分配它..

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

    我不知道,你为什么要根据索引取,理想情况下你应该根据作者的ID写一个查询来获取价值,这样以后就不会产生任何问题了..

    点赞:Authors = new List&lt;Author&gt;() {GetAuthor().FirstOrDefault(x=&gt;x.ID==2)};

    【讨论】:

      【解决方案3】:

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

      编辑:忽略所有这些。您正在使用列表。 你实际上需要的是使用GetRange

      GetAuthors().GetRange(1,1);

      【讨论】:

        猜你喜欢
        • 2021-03-30
        • 2018-11-25
        • 1970-01-01
        • 2021-11-23
        • 2021-10-28
        • 2016-11-24
        • 2013-09-15
        • 2014-07-10
        • 1970-01-01
        相关资源
        最近更新 更多