none
LinQ question RRS feed

  • Question

  • Hi Guys,

    I have the following query:

     

     var groupedCarByCountry = (from car in cars
                                            group car by car.Origine);
    
    
                foreach (var group in groupedCarByCountry )
                {
                    Debug.WriteLine(string.Format("Country Of Origine Is {0}", group.Origine ));
                    foreach (var value in group) 
                    {
                        Debug.WriteLine(string.Format("Brand Name Is {0}", value.Brand ));
                    }
                }
    

     


    How can I cast the query to return the following type?

    IEnumerable<IGrouping<Country, Car>>

    In other words, I want this:

    IEnumerable<IGrouping<Country, Car>>   groupedCarByCountry = (from car in cars
                                                                                                                   group car by car.Origine);
    
    

     

    This is the "cars" list:

    Car[] cars = new Car[3] { new Car{ Brand="toyota", Color ="black", Year =2000, Origine= new Country { Name= "Japan", population  = 110}}, new Car { Brand ="Cadillac", Color ="white", Year = 2010,  Origine = new Country{ Name="USA", population = 200}}, new Car{ Brand ="Lexus", Color="silver", Year =2012, Origine = new Country{ Name="Japan", population=110}}};

     

    Thanks for any help.

     


    • Edited by Amokachi Wednesday, October 5, 2011 3:28 PM
    Wednesday, October 5, 2011 3:02 PM

Answers

  • Hi Amokachi;

    This query which you have posted already returns a collection of IEnumerable<IGrouping<Country, Car>>.

    IEnumerable<IGrouping<Country, Car>> groupedCarByCountry = 
        (from car in cars
         group car by car.Origine);
    

    The only issue I see with your code is that you are incorrectly accessing the Origine variable in the following code snippet :

    foreach (var group in groupedCarByCountry )
    {
        Debug.WriteLine(string.Format("Country Of Origine Is {0}", group.Origine ));
        foreach (var value in group) 
        {
            Debug.WriteLine(string.Format("Brand Name Is {0}", value.Brand ));
        }
    } 
    

    It should be as follows:

    foreach (var group in groupedCarByCountry )
    {
        Debug.WriteLine(string.Format("Country Of Origine Is {0}", group.Key.Name ));
        foreach (var value in group) 
        {
            Debug.WriteLine(string.Format("Brand Name Is {0}", value.Brand ));
        }
    } 
    

    So why do you think that it is NOT returning a IEnumerable<IGrouping<Country, Car>>?

     

     

     

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Wednesday, October 5, 2011 6:00 PM