简体   繁体   English

EF Core 如何使用 linq 将字段存储匹配为字符串但包含由分隔符分隔的项目

[英]EF Core how to use linq to match field stores as string but contains items separated by a delimiter

For example.例如。 This table, I want to search items taged with 'c', not with 'c#' or 'c++'.这个表,我想搜索标有“c”的项目,而不是“c#”或“c++”。 Tags are seperated by a space.标签由空格分隔。

ID  |  BookName              |  Tags 

1   |  C++ Primer            | c++ 
2   | .NET Core 3.1 Tutorial | c# .net
3   | Beginner Tutorial      | c c# c++

Each book record can be marked with multiple tags, If I use每个图书记录都可以标记多个标签,如果我使用

dbContext.Book.Where(a => a.Tags.Contains("c")).ToList()

I'll get all of them.我会得到所有的。 But I only want get Beginner Tutorial .但我只想得到初学者教程 Since I can not use = to filter the Tag field.因为我不能使用=来过滤标签字段。 How can I solve this?我该如何解决这个问题?

PS: I can not change the structure of this table, either. PS:我也不能改变这个表的结构。

You could Split the Tags Fields on delimiter (in your case whitespace) and verify if the tag is present.您可以在分隔符上拆分标签字段(在您的情况下为空格)并验证标签是否存在。 For example例如

var result = dbContext.Book.Where(a => a.Tags.Split(' ').Contains("c"));

You need to first Split Tags by whitespace then you can use Contains or Any您需要首先按空格Split标签,然后您可以使用ContainsAny

By doing this with Contains :通过使用Contains执行此操作:

var result = dbContext.Book.Where(a => a.Tags.Split(' ').Contains("c"));

By doing this with Any :通过使用Any执行此操作:

var result = dbContext.Book.Where(a => a.Tags.Split(' ').Any(t => t.Equals("c")))

These will give you expected result.这些会给你预期的结果。

You can also check difference-between-contains-and-any-in-linq您还可以检查包含和任何在 linq 之间的差异

var result = dbContext.Book.Where(a => a.Tags.Split(' ').Any(t => t.Equals("c")))

You can do it by regex too.您也可以通过正则表达式来完成。

Regex regex = new Regex(@"^c$| c|c ");
var result = books.Where(a => regex.Match(a.Tags).Success);

Modify your model as follows :修改您的模型如下:

public string Tags
    {
        get
        {
            return TagsList != null
                ? String.Join(" ", TagsList.Select(tag => tag ))
                : null;
        }
        set
        {
            TagsList = !String.IsNullOrWhiteSpace(value)
                ? value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList()
                : new List<string>();
        }
    }

[NotMapped]
public List<string> TagsList { get; set; }

Then use :然后使用:

dbContext.Books.Where(a=>a.TagsList.Contains("c"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM