比较一个数组和另一个数组的对象

本文关键字:数组 另一个 对象 一个 比较 | 更新日期: 2023-09-27 18:17:15

我有一个模型组:

public class GroupModel
{
    [Key]
    public int GroupModelId { get; set; }
    [Required]
    [MaxLength(50)]
    [DataType(DataType.Text)]
    public string GroupName { get; set; }
    [Required]
    public virtual ICollection<FocusArea> FocusAreas { get; set; }
    ...

和一个模型Focus:

public class FocusArea
{
    public int FocusAreaId { get; set; }
    public FocusEnum Focus { get; set; }
    public List<ApplicationUser> ApplicationUser { get; set;  }
    public virtual ICollection<GroupModel> GroupModel { get; set; }

public enum FocusEnum
{
    Psych,
    Medical,
    LivingWith
}

Group和Focus具有多对多关系。我的控制器正在接收:

public ActionResult GroupSearch(string[] focusSelected) // Values possible are Pysch, Medical and LivingWith
{
    List<GroupModel> groups;
    ...

问题:我想选择在focusSelected数组内具有所有焦点的组。

我试过了:

groups = groups.Where(t => t.FocusAreas.Where(x => focusSelected.Contains(x.Focus))).ToList()).ToList();

显然不工作。有人有别的想法吗?

比较一个数组和另一个数组的对象

这可能对你有帮助

 var result = groups.Where(g => g.FocusAreas.All(f => focusSelected
              .Any(fs => (FocusEnum)Enum.Parse(typeof(FocusEnum), fs, true) == f.Focus)));

Where需要一个返回bool的委托/表达式。在您的示例中-您将Where放入Where中,其中Where返回集合。将内部Where更改为All应该可以做到:

var allSelParsed = focusSelected.Select(s => (FocusEnum)Enum.Parse(typeof(FocusEnum), s)
                                .ToList();
groups = groups.Where(gr => allSelParsed.All(selected => 
                                                gr.FocusAreas.Any(fc => 
                                                                    fc.Focus == selected)))
               .ToList();

这应该会给你预期的结果

var result = groups.Where(g => 
                      focusSelected.All(fs => 
                          g.FocusAreas.Any(fa => fa.ToString() == fs)));