为了账号安全,请及时绑定邮箱和手机立即绑定

从表中检索所有项目,其中表列的文本包含在项目列表中

从表中检索所有项目,其中表列的文本包含在项目列表中

C#
哈士奇WWW 2023-09-16 20:03:10
我有一个名为策略的表,其中包含许多应对策略:[    {        "id": 6,        "title": "Coping with Depression",        "description": "A coping strategy for depression.  A description of the coping strategy. \r\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",        "topic": "depression"    },    {        "id": 18,        "title": "Coping with Stress",        "description": "A coping strategy for stress. A description of the coping strategy. \r\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",        "topic": "stress"    }]该表中的一列称为“主题”,可以包含多个主题字符串,例如“压力抑郁”等。上面的示例数据说明了可行的场景,其中“主题”列中只有一个主题字符串。我的代码如下:var listOfTerms = new List<string>() { "stress", "depression" };var strategies = _context.Strategies      .Where(strategy => listOfTerms.Any(t => t.Equals(strategy.Topic)))      .ToListAsync();我也尝试过:var strategies = _context.Strategies   .Where(strategy => listOfTerms.Any(t => t.ToLower().Contains(strategy.Topic.ToLower())))   .ToListAsync();这段代码适用于上面所示的场景,即 Topic 列中只有一个 Topic 字符串。如果我将主题字符串“stress”添加到场景 id = 6 的主题列中,那么该行将不会返回到策略列表中。因此,总之,我想从 _context.Strategies 表中检索所有项目,其中strategy.Topic列的文本包含在listOfTerms中项目的文本中,如果strategy.Topic列的文本可以包含多个项目一个主题字符串。任何帮助将不胜感激。
查看完整描述

1 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

好吧,我想我终于明白你的问题了。

鉴于:

class Problem{
    public string topic { get; set; }
}

如果我这样设置:

List<Problem> problems = new List<Problem>();
problems.Add(new Problem { topic = "stress" });
problems.Add(new Problem { topic = "depression" });
problems.Add(new Problem { topic = "stress, depression" });

然后创建一个术语列表:

var listOfTerms = new List<string>() { "stress", "depression" };

然后我可以得到你想要的结果:

var result = problems.Where(item => listOfTerms.Any(term => item.topic.Contains(term))).ToList();

该 linq 语句让我回到了所有三个“问题”。


查看完整回答
反对 回复 2023-09-16
  • 1 回答
  • 0 关注
  • 55 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信