Search code examples
c#wpfmvvmcsla

Optimizing my Search function using foreach() - perfomance


Here is the deal. I have got 3 Tables.

  1. Main ( contains ID and a list of SubMain ) ~ 130 items (after first filtering)

  2. SubMain (contains SubMainID) ~ 120 items (which got a n to m reference so there is an other table)

  3. MainToSub ( contains ID, MainID and SubMainID) ~ 500 items

Main is my Model which im working with and which I display in the GridView. With this foreach I search for every Model part which has SearchSubMainID in it. This works but the problem is that i am jumping more then 72000 into the foreach which isn't really optimized

foreach (var item in MainToSub)
{ 
 // 500 Jumps
    foreach (var temp in Main)
    {
        if (item.MainID == temp.ID && item.SubMainID == SearchSubMainID)
        {
            Model.Add(temp);
            // ~ 10 Jumps
        }
       // 72000 jumps
    }
}

Question: Is there a way to optimize the foreach?


Solution

  • Well, you could move one of the checks up one foreach:

    foreach (var item in MainToSub)
        if (item.SubMainID == SearchSubMainID)
            foreach (var temp in Main)
                if (item.MainID == temp.ID)
                    Model.Add(temp);
    

    And this isn't really optimization, but you could also turn it into a LINQ expression:

    foreach (var temp in MainToSub
        .Where(i => i.SubMainID == SearchSubMainID)
        .Join(Main, i => i.MainID, t => t.ID, (i, t) => t))
            Model.Add(temp);