I have written the following code:
//get the user from the DB
var tmpuser = _db.aspnet_Users.First(q => q.UserName == user.Identity.Name);
//list the direct connections to Verbond
List<Verbond> verb1 = tmpuser.UsersVerbondens
.Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
.Select(q => q.Verbond)
.ToList();
//list the connected Facturatieverbonden
List<FacturatieVerbonden> verb2 = tmpuser.UsersFacturatieVerbondens
.Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
.Select(q => q.FacturatieVerbonden)
.ToList();
//loop through the facturatieverbonden and add their verbonds to the first list
foreach (FacturatieVerbonden v in verb2) {
verb1.AddRange(v.Verbonds);
}
//make a distinct list
List<Verbond> test = verb1.Distinct().ToList();
So, Users can be connected to 0 or more facturatieverbonden and also can be connected to verbond.
A facturatieverbonden can have one or more verbond‘s under itself.
What I need is a list of all the verbond‘s the user is connected to, directly, or indirectly via the facturatieverbonden.
My code works but I don’t think it’s very efficient. Any hints on making it cleaner?
Your query isn’t very LINQy. Here’s a potential improvement:
By making
ToListthe very last thing it does, the whole computation can be done in the database, avoiding all the intermediate lists.