如何通过列表中的属性值获取/查找对象 [英] How to get/find an object by property value in a list
本文介绍了如何通过列表中的属性值获取/查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题,关于使用LINQ通过搜索"它们的字段名称来获取列表对象.我已经为此编写了简单的Library
和Book
类:
I have a question about getting a list objects by "searching" their field names using LINQ. I've coded simple Library
and Book
classes for this:
class Book
{
public string title { get; private set; }
public string author { get; private set; }
public DateTime indexdate { get; private set; }
public int page { get; private set; }
public Book(string title,string author, int page)
{
this.title = title;
this.author = author;
this.page = page;
this.indexdate = DateTime.Now;
}
}
class Library
{
List<Book> books = new List<Book>();
public void Add(Book book)
{
books.Add(book);
}
public Book GetBookByAuthor(string search)
{
// What to do over here?
}
}
所以我想获取某些字段等于某些字符串的Book
实例,例如
So I want to get Book
instances which certain fields is equal to certain strings, like
if(Book[i].Author == "George R.R. Martin") return Book[i];
我知道使用简单的循环代码是可能的,但是我想使用LINQ做到这一点.有什么办法可以做到这一点?
I know it's possible with simple loop codes but I want to do this with LINQ. Is there any way to achieve this?
推荐答案
var myBooks = books.Where(book => book.author == "George R.R. Martin");
并记得添加:using System.Linq;
在您的特定方法中,由于您只想退回一本书,因此您应该写:
In your specific method, since you want to return only one book, you should write:
public Book GetBookByAuthor(string search)
{
var book = books.Where(book => book.author == search).FirstOrDefault();
// or simply:
// var book = books.FirstOrDefault(book => book.author == search);
return book;
}
Where
返回FirstOrDefault
返回在可枚举中找到的第一本书;如果未找到,则返回null
.
这篇关于如何通过列表中的属性值获取/查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文