(C#)LINQ —使用方法.Contains()

我有两个查询,分别按名称搜索Authors和按标题搜索Books。第一个按预期方式工作,它正在查看是否有任何作者的姓名包含我的输入。由于某些原因,我无法对这些书的书名进行相同的处理。我收到一条错误消息,说我知道 char ...

时,我无法对string采取行动

它们之间的唯一区别是我使用的是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»输出=>玛格丽特·阿特伍德


按“书名”查询(不起作用)

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),但稍后收到一条错误消息,告诉我转换输出时无法获取空值。ToList()


课堂书

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.
}
bellebei 回答:(C#)LINQ —使用方法.Contains()

where book.Title.Any(x => x.Contains(searchTerm))

将不会编译,因为您正在将Title分解为chars的集合。它说:给我所有具有标题的书,每个字符包含我的搜索词。

我想你想要

where book.Title.Contains(searchTerm))

这说:给我所有带有标题的书,其中包含搜索词。

从您的评论看来,有些书的标题为空。在这种情况下,我们需要注意这一点,否则Title.Contains将抛出NullReferenceException

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

这是说:给我所有标题不为null且不为空且包含searchTerm的书。

最后,您可能要确保搜索不区分大小写。

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
,

您的属性Titlestring,在包括C#在内的大多数语言中,string实际上是char的数组

linq查询Any在数组上进行迭代,因此,由于属性是string,其本身就是char[],因此我检查Any还是char与谓词匹配。

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

where book.Title.Contains(InputBook.Text)
本文链接:https://www.f2er.com/3069147.html

大家都在问