1

If I have list of Author objects like

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

this example is actually wrapped in static method which returns list of authors.

Inside my other object there is property Authors of type List<Author>. Now I want to assign second author from the list to Authors property.

I thought that I can use Authors = GetAuthors()[1].ToList(); but I cannot access ToList() on index specified author.

to clarify

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>
};
2
  • not sure I understand your question do you need Authors = new List<Author>(){someObject[1]}; ? Commented Oct 16, 2013 at 9:55
  • I just needed to instance new List<Author>() and than assing index specified author, like it was answered below Commented Oct 16, 2013 at 9:56

3 Answers 3

1

If I understand you correctly, you want a List<Author> with a single author in it. Using ToList() on a single Author object is then not valid syntax.

Try this: Authors = new List<Author>() { GetAuthors()[1] };

Sign up to request clarification or add additional context in comments.

Comments

0

You can't assign a single author to list<Author>, so you will have to create a list (of single author) to assign it..

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

I don't know, why you want to take based on index, ideally you should write a query based on ID of author to get value, so that it won't create any issue in future..

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

Comments

0

A sollution with LINQ would be GetAuthors().Skip(1).Take(1)

Edit: Ignore all that. You're working with lists. What you actually need is to use GetRange:

GetAuthors().GetRange(1,1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.