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

384 views Asked by At

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?

2

There are 2 answers

0
Stephen Brickner On BEST ANSWER

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 
5
Hopeless On

You can use Except to exclude the hobbies of a person from all hobbies:

var obj = db.Hobbies_tbl.Except(Person.PersonHobbies_tbl);

I think using Except has better performance than Contains because there is some internal HashSet used to implement the excepting operation.