Muhammad Mudassar
Muhammad Mudassar

Reputation: 157

Linq Query to get List of Objects and for Each of Object get another nested List

In my MVC application I want to get all the Tests which are parent of Headings, Headings are parent of Parameters and Parameters are Parent of Drop Downs, like:

Tests --> List of Headings-->List of Parameters -->List of Drop Downs

In my Controller I am trying to get lists with in list:

var getAllReport = (
           from tests in _db.tblPatientSelectedTests.ToList()
           from heading in _db.tblHeadings.Where(x=>x.TestID == tests.TestId).ToList()
           from par in _db.tblParameters.Where(x=>x.HeadingID == heading.HeadingID).ToList()
           from drp in _db.DropDownValues.Where(x =>x.ParemeterID == par.ParameterId).ToList()
           select new
           {
               Tests = tests,
               Headings = heading,
               Parameters = par,
               DropDowns = drp
           }
           ).ToList();
ViewBag.GetAllReports = getAllReport;

I want it to be strongly typed, so I have tried to make a class like this:

public class allparams
    {
        public List<tblPatientSelectedTest> Tests { get; set; }
        public List<tblHeading> Headings { get; set; }
        public List<tblParameter> Parameters { get; set; }
        public List<DropDownValue> DropDowns { get; set; }
    }

I want to use that class allparams in my linq so I can have strongly typed view.

I want to populate results in my view like this:

@foreach(Tests item in ViewBag.GetAllReports)
{
 do some stuff 
@foreach(Headings item in ViewBag.GetAllReports)
 {
  do some stuff and so on for other nested lists 
 }
}

Upvotes: 0

Views: 477

Answers (1)

Anis Ahmad
Anis Ahmad

Reputation: 46

I suppose you are using EF.

Your problem can be solved through Linq's Include() method.

var getAllReport = _db.tblPatientSelectedTests
.Include("tblHeadings")
.Include("tblParameters")
.Include("DropDownValue")
.ToList();

The Include() allows you to fetch the related entities from the database as part of the same query. The details can be seen here.

And later you can just use it as follows:

@foreach(Tests test in ViewBag.GetAllReports)
{
    //do some stuff 
    @foreach(Headings heading in test.tblHeadings)
    {
        //do some stuff and so on for other nested lists 
        //and so on... for tblParameters and DropDownValue
    }
}

Just a suggestion though, the data access logic should be kept in a separate layer for maintainability reasons.

Upvotes: 3

Related Questions