Emilio Weba
Emilio Weba

Reputation: 312

Compare object with an array with another array

I have a model Group:

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; }

    ...

And a model 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 and Focus has a many-to-many relationship. My Controller is receiving:

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

    ...

Problem: I want to select the groups that have all the focus that are inside the focusSelected array.

What I've tried:

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

Obviously not working. Does anyone have another idea?

Upvotes: 2

Views: 85

Answers (3)

Arghya C
Arghya C

Reputation: 10078

This should give you expected result

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

Upvotes: 0

pwas
pwas

Reputation: 3383

Where needs a delegate / expression that returns bool. In your sample - you are putting Where inside Where, where Where returns collection. Changing inner Where to All should do the trick:

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();

Upvotes: 0

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32521

This may help you

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

Upvotes: 1

Related Questions