Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何通过列表中的属性值获取/查找对象_C#_Linq - Fatal编程技术网

C# 如何通过列表中的属性值获取/查找对象

C# 如何通过列表中的属性值获取/查找对象,c#,linq,C#,Linq,我有一个关于使用LINQ“搜索”对象的字段名来获取对象列表的问题。我已经为此编写了简单的Library和Book类: class Book { public string title { get; private set; } public string author { get; private set; } public DateTime indexdate { get; private set; } public int page { get; privat

我有一个关于使用LINQ“搜索”对象的字段名来获取对象列表的问题。我已经为此编写了简单的
Library
Book
类:

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?
    }
}
我知道使用简单的循环代码是可能的,但我想用LINQ实现这一点。有没有办法做到这一点

var myBooks = books.Where(book => book.author == "George R.R. Martin");
并记住添加:
使用System.Linq

在您的特定方法中,由于您只想返回一本书,您应该写:

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;
}
返回一个
IEnumerable
,然后返回在可枚举中找到的第一本书,如果没有找到任何书,则返回
null

var books = books.Where(x => x.author == search).ToList();
您的Book方法返回一本书,我建议您返回一个列表,因为该作者可能有多本书。

您可以这样使用:

public Book GetBookByAuthor(string search)
{
    return books.FirstOrDefault(c => c.author == search);
}

我建议使用IndexOf而不是简单的等式来避免大小写问题

var myBooks = books.Where(x => x.author.IndexOf("George R.R. Martin", StringComparison.InvariantCultureIgnoreCase) >= 0);
或者,如果您只找到列表中的第一本书中的一本,请使用

var myBook = books.FirstOrDefault(x => x.author.IndexOf("George R.R. Martin", StringComparison.InvariantCultureIgnoreCase) >= 0);

使用公共var和私有setter的原因是什么?@icbytes,Book类是一个不可变的对象,在多线程代码中非常有用。在本例中,没有理由修改book对象。您从哪里知道这一点?因为该类默认为私有类?问题应该是“如何通过其字段内容获取/查找对象”,不是字段名。
GetBookByAuthor
方法返回类型是
Book
not
IEnumerable
,因此在使用
FirstOrDefault
或将方法返回类型更改为
IEnumerable
之前,这是不起作用的。是的,我也看到了。现在,实现符合OP的要求
var myBook = books.FirstOrDefault(x => x.author.IndexOf("George R.R. Martin", StringComparison.InvariantCultureIgnoreCase) >= 0);