none
Linq Query for for loop

    Question

  • Please suggest me linq query for below for loop. I need to marked IsChecked = True in ProductCategories collection if the ProductCategoryID is matches in ProductToProductCategories collection.

    for (int i = 0; i < ProductCategories.Count; i++)
    {
          for (int j = 0; j < ProductToProductCategories.Count; j++)
         {
               if (ProductCategories[i].ProductCategoryID == ProductToProductCategories[j].ProductCategoryID)
              {
                      ProductCategories[i].IsChecked = true;
               }
         }
     }

    Note: ProductCategories & ProductToProductCategories both are ObservableCollection<ProductCategory> & ObservableCollection<ProductToProductCategories>
    Wednesday, November 13, 2013 10:16 AM

Answers

  • Hi Bikram;

    The following code snippet should do the same as your code using linq.

    // The query will return all ProductCategories object that needs to have 
    // there IsChecked changed to true.
    var results = (from p in ProductCategories
                   from pc in ProductToProductCategories
                   where p.ProductCategoryID == pc.ProductCategoryID
                   select p).ToList();
    
    // Now take the results of the query and actualy change IsChecked.
    foreach (var productCategory in results)
    {
        productCategory.IsChecked = true;
    }
    
    // At this point all the values have been changed in ProductCategories collection.

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Wednesday, November 13, 2013 7:16 PM