对于按名称搜索Authors和按标题搜索Books,我有两个查询。第一个是按预期工作的,它查看是否有任何作者的名字包含我的输入。出于某种原因,我不能对书的标题做同样的事。我收到一个错误,说我不能对char采取行动当我知道是astring.
它们之间唯一的区别是,我使用的是List<string> Names和string Title
Author names查询(工作)
author = from book in Serialisation.Books
where book.Author.Names.Any(author => author.Contains(InputBook.Text))
select book;当我在author => author上悬停时,它告诉我它是一个字符串参数。属性名是一个List<string> Names,因为有些书可能有两个作者。我能够找到任何作者的名字,与只需一个字母的搜索相对应。
例如:M输出=>玛格丽特·阿特伍德
Book titles查询(不工作)
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()时不能获得空值。
类册
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.
}发布于 2019-11-20 02:37:47
where book.Title.Any(x => x.Contains(searchTerm))不会编译,因为您正在将标题解构为一个字符集合。它说:给我所有的书,其中有一个标题,每一个字符包含我的搜索词。
我想你想
where book.Title.Contains(searchTerm))这是说:给我所有的书,其中有一个标题,其中包含搜索词。
从你的评论来看,似乎有一些书名为零的书。在这种情况下,我们需要防范这种情况,否则Title.Contains将抛出NullReferenceException
where !string.IsNullOrEmpty(book.Title) &&
book.Title.Contains(searchTerm)这是这么说的:给我所有的书名,标题都不是空的,并且包含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发布于 2019-11-20 02:42:15
属性Title是string,在包括C#在内的大多数语言中,string实际上是一个char数组。
linq查询Any在数组上迭代,因此由于属性是一个string (它本身就是一个char[] ),所以我检查Any或char是否匹配谓词。
您要寻找的是比较字符串本身,如果它包含其他字符串。为此,您需要使用:
where book.Title.Contains(InputBook.Text)https://stackoverflow.com/questions/58945764
复制相似问题