Search code examples
c#asp.net-mvcentity-frameworkcontrollerdatalistitem

Reverse result of a partition from a list using Entity Framework and ASP.NET MVC


Lets say I have three tables(Person_tbl, PersonHobbies_tbl and Hobbies_tbl) with relationships between them like:

Person_tbl [1]-------[n] PersonHobbies_tbl [n]-------[1] Hobbies_tbl

The logic is that a specific person can have more hobbies. I want to retrieve a list of hobbies which are not assigned to a specific person represented by it`s ID.

For example if I want to get a list of hobbies which is assigned to a specific person, I can do this like:

DBEntity db = new DBEntity();

var Person = db.Person_tbl.Find(id); //id contains the ID of a person
var obj = Person.PersonHobbies_tbl;

//lets say that ViewListResult cointains only HobbyName
return obj.Select(n => new ViewListResult   
{
    HobbyName= n.Hobbies_tbl.name
}).ToList();

I want to obtain the opposite of this(a list with the rest of the hobbies) in a efficient way.

So my question is how can I solve my problem in a efficient enough way?


Solution

  • A quick linqpad test that should get you what you need.

    void Main()
    {
        var hobbies = new List<Hobby>()
        {
            new Hobby { ID = 1, Name = "Test 1" },
            new Hobby { ID = 2, Name = "Test 2" },
            new Hobby { ID = 3, Name = "Test 3" },
            new Hobby { ID = 4, Name = "Test 4" }
        };
    
        var ids = new[] { 2, 3 };
    
        var rest = hobbies.Where(x => !ids.Contains(x.ID)).ToList();
        rest.Dump();
    }
    
    public class Hobby
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    
    
    ID  Name
    1   Test 1 
    4   Test 4