使用Linq搜索实体列表中是否存在所有属性

本文关键字:存在 属性 是否 Linq 搜索 实体 列表 使用 | 更新日期: 2023-09-27 17:59:50

我有以下实体:

[Table("Entities")]
public abstract class Entity { 
 public int EntityID { get; set; } 
 public string Description { get; set; }
 public virtual ICollection<Tag> Tags { get; set; }
}

标签实体:

public class Tag {
    public int TagID { get; set; }
    public int EntityID { get; set; }
    public string TagValue { get; set; }
}

如上所述,标签是而不是重复使用的,只是存储为字符串。这使得确定实体是否共享标记变得稍微困难(而且速度较慢)。

我有一个工作搜索来返回实体列表,其中实体包含任何标签:

List<string> searchTags = new List<String> {"test1", "test2"};
entities = (_entityRepository.Entities
            .Where(o=>o.Tags.Any(f=>searchTags.Contains(f.TagValue)));

现在我还需要返回一个实体列表,其中包含列表中的所有标记。由于非属性变量不能传递到Contains方法中,我不能用all来反转调用的顺序,但这基本上是我想要实现的:

entities = (_entityRepository.Entities
            .Where(o=>o.Tags.All(f=>f.TagValue.Contains(searchTags)));

我想我刚刚达到了需要纠正DB模式以重用标签的地步,这应该在过滤标签列表上的实体时提供一般的性能优势,但我仍然想问以下问题:

  1. 我是不是过于复杂了,有没有一个简单的Linq语句可以实现这一点,或者
  2. 这是我应该使用谓词生成器来设置标准的东西吗

使用Linq搜索实体列表中是否存在所有属性

这可以这样做:

var query = _entityRepository.Entities.Select(e => e);
query = searchTags.Aggregate(query, (current, tag) => current.Where(e => e.Tags.Any(t => t.TagValue == tag)));
var result = query.ToList();