I have a set of classes as follows:
public class ResponseWrapper
{
public IEnumerable<Book> data { get; set; }
}
public class Book
{
public List<Author> author_data { get; set; }
public string isbn13 { get; set; }
public string publisher_name { get; set; }
public string title { get; set; }
}
public class Author
{
public string name { get; set; }
public string id { get; set; }
}
A Book class contains a list of child Author items. In my case I'm trying to select the 'name' property of the first Author item in the collection.
I thought I'd be able to select it using:
string author = response.data.Where(b => b.author_data.Any()).Select(b => b.author_data.FirstOrDefault().name);
however that won't compile and I think it's because Select returns a collection? Where as I'm just trying to get a single result.
Can anyone tell me the correct linq statement I need to get the single result I'm after?
Thanks
I think you're over-complicating things. You can select the first item just by using First()
or FirstOrDefault()
.
string author = response.data.First().author_data.First().name;
Just make sure you gaurd for null
though.
string author = string.Empty;
Book firstBook = response.data.FirstOrDefault();
if (firstBook != null && firstBook.author_data.Any())
{
author = firstBook.author_data.First().name;
}
尝试这个
string author = response.data.Where(b => b.author_data.Any()).FirstOrDefault().author_data.FirstOrDefault().name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.