(C#) LINQ — 使用方法 .Contains() 找不到任何结果

(C#) LINQ — Cannot find any result with method .Contains()

我有两个查询,分别按名称搜索 Authors 和按标题搜索 Books。第一个按预期工作,它正在查看是否有任何作者的名字包含我的输入。出于某种原因,我不能对书名做同样的事情。当我知道 它是 一个 string...

时,我收到一条错误消息说我无法对 char 采取行动

它们之间的唯一区别是我使用的是 List<string> Namesstring Title


按“作者姓名”查询(有效)

author = from book in Serialisation.Books
         where book.Author.Names.Any(author => author.Contains(InputBook.Text))
         select book;

当我将鼠标悬停在 author => author 上时,它告诉我这是一个字符串参数。 属性 名字是 List<string> Names 因为有些书可能有 2 位作者。我能够找到与仅用一个字母的搜索相对应的任何作者姓名。

例如:« M » 输出 => Margaret Atwood


按“书名”查询(无效)

book = from book in Serialisation.Books
       where book.Title.Any(x => x.Contains(InputBook.Text))
       select book;

在这里,当我将鼠标悬停在 x => x 上时,它告诉我这是一个 char 参数,因此我不能使用方法 .Contains()...

我得到的唯一解决办法是改写这个:

book = from book in Serialisation.Books
       where book.Title == InputBook.Text
       select book;

这当然不是我想要的。我不知道要改变什么才能让它发挥作用..

编辑: 我试过 book.Title.Contains(InputBook.Text),后来我收到一条错误消息,告诉我在转换 output.ToList()

时无法获得空值

Class 书

public class Book 
{
    public string Title { get; set; }
    public Author Author { get; set; }
    // my other class Author is simply a list of names. 
    // I need it to override the method ToString() so that 
    // when there is two authors for the same book, I only have 
    // one string to look into for my query.
}
where book.Title.Any(x => x.Contains(searchTerm))

无法编译,因为您正在将 Title 解构为 collection 个字符。它说:给我所有标题中每个字符都包含我的搜索词的书。

我想你想要

where book.Title.Contains(searchTerm))

意思是:给我所有标题包含搜索词的书。

从您的评论看来,有些书的书名是空的。在这种情况下,我们需要防范这种情况,否则 Title.Contains 将抛出 NullReferenceException

where !string.IsNullOrEmpty(book.Title) &&
               book.Title.Contains(searchTerm)

这表示:给我所有标题不为 null 且不为空且包含 searchTerm 的图书。

最后,您可能要确保搜索 case-insensitive。

where !string.IsNullOrEmpty(book.Title) &&
               book.Title.Contains(searchTerm, StringComparison.InvariantCultureIgnoreCase)

测试

string searchTerm = "Adventures";
var books = new [] { 
    new Book{Title = "Adventures in Code"},
    new Book{Title = "My adventures in Oz"},
    new Book{Title = "About Linq"},
    new Book{Title = null} // no title
    };
var found = from book in books
        where !string.IsNullOrEmpty(book.Title) &&
               book.Title.Contains(searchTerm, StringComparison.InvariantCultureIgnoreCase)
        select book;
foreach( var b in found ) Console.WriteLine(b.Title);

输出

Adventures in Code
My adventures in Oz

你的 属性 Title 是一个 string 并且在包括 C# 在内的大多数语言中,string 实际上是 char 的数组

linq 查询 Any 正在数组上迭代,因此由于 属性 是一个 string,它本身是一个 char[] 我检查是否Anychar 匹配谓词。

您要查找的是比较字符串本身是否包含其他字符串。因此你需要使用 :

where book.Title.Contains(InputBook.Text)