Tuesday, August 02, 2011


How to Query Objects inside Objects using LINQ

Using LINQ you can avoid for each loop completely by using LINQ query, LINQ is much faster than Loop. I am giving one example below to clarity this

Assume you have some Object structure like below, One object has reference to others

    public class Country
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public List<States> State { get; set; }
    } 
    public class States
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public List<City> City { get; set; }
    } 
    public class City
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public List<Area> Area { get; set; }
    } 
    public class Area
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }
  
You have some data in it and which will in the form of parent child relationship

Ex:

-India  
---MP
----Jabalpur
------Street no 300

Like this you have 1000 of Country data. And your requirement to update the Area of each country  

You have loaded data in following Object and declared globally to use

List<Country> _country = new List<Country>();

To achieve this one way is to loop through till child most and update the data like below

One Way

foreach (Country cn in _country)
{
   foreach (States st in cn.State)
   {
      foreach (City ct in st.City)
       {
         foreach (Area ar in ct.Area)
          {
            if (ar.Id == id)
             {
               Ar.Name = “Updated Name here”;
             }
           }
        }
     }
 }

Second Way

Now look into other way of doing the same using LINQ to Object

 (from ctn in _country
     from st in ctn.State
       from ct in st.City
         from ar in ct.Area
           select ar).Where(s => s.Id == id)
             .ToList<Service>().ForEach(a => 
                      { a.Name = “Updated Name here”});

Conclusion: LINQ query is much more efficient to do this kinds of work and using this you can gain 90% fast performance avoiding Loops inside Loops.

No comments: