string searchByTags = "politics, economy";
char[] delimiters = new[] { ',', ';', ' ', '#' }; // List of your delimiters
List<string> providedTags = null;
if (searchByTags != null)
{
providedTags = searchByTags.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).ToList();
}
ViewNotesVM vnVM = new ViewNotesVM();
vnVM.Quotes = db.SavedQuotes.Where(s => s.Tags.Any(x => (searchByTags != null) ? providedTags.Any(y => y == x.Name) : true)).ToList();
所有“SavedQuotes”都有一些“标签”。这是一个名为“Tag”的简单类,它具有“Name”属性。它作为ICollection存储在SavedQuotes中。
我想要做的是显示数据库中的所有“SavedQuotes”,其中包含“searchByTags”变量中给出的标记。
但是我的代码存在一些问题。 Visual Studio显示错误:
无法创建类型为“System.Collections.Generic.List”的空常量值。在此上下文中仅支持实体类型,枚举类型或基元类型。
我的代码出了什么问题,我怎样才能做得更好?
答案 0 :(得分:1)
您可以做的是简化查询,以便将其翻译成SQL。此外,您应该将它分成两个单独的查询,分别针对您尝试解决的两个不同案例:
你可以这样做:
private static readonly _emptyTags = new List<string>();
// ...
// Get list with applicable tags.
List<string> providedTags = (searchByTags != null)
? providedTags = searchByTags.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).ToList();
: _emptyTags;
// ...
// Split based on whether any tags were provided as a filter.
if (providedTags.Length > 0)
{
// Filter by tags
vnVM.Quotes = db.SavedQuotes
.Where(s => s.Tags.Any(t => providedTags.Contains(t.Name)))
.ToList();
}
else
{
// Get them all
vnVM.Quotes = db.SavedQuotes.ToList(); // note: unbounded result set.
}