我有DbSet<DtoProfile>
。
现在我想过滤我的个人资料。
我的模特:
public class DtoProfile {
public IList<DtoLookingFor> LookingFor { get; set; } = new List<DtoLookingFor>();
public virtual DtoSearch Search { get; set; }
public Guid? SearchId { get; set; }
}
public class DtoLookingFor
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public LookingFor LookingFor { get; set; }
}
public enum LookingFor
{
A, B, C, D, E
}
public class DtoSearch
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public virtual ICollection<DtoLookingFor> LookingFor { get; set; }
}
实施例:
Profile1具有LookFor A,B,C并使用LookingFor B,C
来搜索
Profile2有LookFor B,D
Profile3有LookFor E
Profile1应该获取LookingFor为B或C的所有配置文件(在示例中为Profile1和Profile2)
如何使用IQueryable<DtoProfile>
执行此操作?
我已经从数据库中加载了DtoSearch,并且可以使用dtoSearch.Looking来访问所有DtoLookingFor
答案 0 :(得分:0)
我会更改名为“LookingFor”的属性,真的很混乱,你有太多这些,它也是类名。
如果您选择输入profile1 - > gt,此工作示例将为您带来profile1 + profile2
static void Main(string[] args)
{
List<DtoProfile> profiles = new List<DtoProfile>();
var profile1 = new DtoProfile
{
LookingFor = new List<DtoLookingFor> { new DtoLookingFor { LookingFor = LookingFor.A }, new DtoLookingFor { LookingFor = LookingFor.B }, new DtoLookingFor { LookingFor = LookingFor.C } },
Search = new DtoSearch
{
LookingFor = new List<DtoLookingFor> { new DtoLookingFor { LookingFor = LookingFor.B }, new DtoLookingFor { LookingFor = LookingFor.C } },
},
SearchId = new Guid("10000000-0000-0000-0000-000000000000")
};
var profile2 = new DtoProfile
{
LookingFor = new List<DtoLookingFor> { new DtoLookingFor { LookingFor = LookingFor.B }, new DtoLookingFor { LookingFor = LookingFor.D } },
SearchId = new Guid("20000000-0000-0000-0000-000000000000")
};
var profile3 = new DtoProfile
{
LookingFor = new List<DtoLookingFor> { new DtoLookingFor { LookingFor = LookingFor.E } },
SearchId = new Guid("30000000-0000-0000-0000-000000000000")
};
profiles.AddRange(new List<DtoProfile> { profile1, profile2, profile3 });
IEnumerable<DtoProfile> query = GetMatchesForProfile(profiles, profile1);
Console.WriteLine("Found: " + string.Join(",", query.Select(m => m.SearchId)));
//result: Found: 10000000-0000-0000-0000-000000000000,20000000-0000-0000-0000-000000000000
}
private static IEnumerable<DtoProfile> GetMatchesForProfile(List<DtoProfile> profiles, DtoProfile profileToMatch)
{
return profiles.Where(searchProfile => profileToMatch.Search.LookingFor.Any(m => searchProfile.LookingFor.Any(z => z.LookingFor == m.LookingFor)));
}