none
grouping and returning values using linq RRS feed

  • Question

  • Hello,

    I am new to LINQ and need some help with the following basic query. I have in a table a list of states that could have rows with with the same state.

    I need to group the states and then display the state and the total count for each state. Eg: CA (3), FL (1), AZ (5).

    My table looks something like this:

    I have been able to perform this query on a test page with a test list and then i am able to display it in a control.

    My Linq query is: 

    varmyResult = froms inloc.GroupBy(p => p.State)

    orderbys.Key

    selectnew                          

    {

       State = s.Key

                               };

    " ("+ (fromct inloc wherect.State == s.Key selectct.State).Count() + ")"

    vardubarray = myResult.ToArray();

    My problem is that I have this query in a class I do not know how to pass the var as a parameter and thus access the data. I have been plugging away for a couple of days now and am not sure which direction to go.

    Any help would be appreciated.

    Thank you.

    Thursday, September 20, 2012 7:17 PM

Answers

  • Hi Fernando,

    I got it sorted. I cleaned up my code and built some basic pages and classes from scratch.

    I was able to use the:

    foreach (StateResult itemin chk.GetStates())                
    {  
        lstTestData
    .Items.Add(item.State);
    }

    I also had to clean up the group statement in the linq query as it was working fine when I created a temp list in code to query but then when I queried the db I got some errors.

    I was also looking at this link, but have not had time to go through and implemetn it to see if it would work for me:

    http://devtechnospot.wordpress.com/2011/11/07/return-anonymous-type-from-c-method/

    This grouping example also helped me:

    http://stackoverflow.com/questions/1634830/counting-items-in-grouped-results-in-linq-to-sql

    Many thanks for your help. I do understand it a bit more but need more flight time as I am new to Linq and very weak on it. I shall persevere.

    Thanks again,

    Regards.....



    • Marked as answer by uzzitt Tuesday, September 25, 2012 10:00 PM
    • Edited by uzzitt Tuesday, September 25, 2012 10:01 PM
    Tuesday, September 25, 2012 10:00 PM

All replies

  • Hi uzzitt;

    To your question, "I have this query in a class I do not know how to pass the var as a parameter and thus access the data.", Because the query is returning an anonymous type the compiler creates a name for it which we do not know what it is and therefore can not pass it as a parameter. To resolve this issue what you should do is create a class as the one below called StateResult. Then modify the link query as shown below. Please note that I am returning a List<StateResult> which is the data type to use in the signature of the function that you will call. If this really needs to be an array then switch the ToList() to ToArray() and it will return an array of StateResult.

    var myResult = (from s in loc.GroupBy(p => p.State)
                    orderbys.Key
                    select new StateResult
                    {
                        State = s.Key,
                        Count = s.Count()
                    }).ToList();
    
    
    public class StateResult
    {
        public string State { get; set; }
        public int Count { get; set; }
    }

      


    Fernando (MCSD)

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

    Thursday, September 20, 2012 7:39 PM
  • Hi Fernando,

    Thank you for your response. I have taken what you said and implemented, but am still not able to get the string output from the list into a list box onto my form.

    In my class, I have this:

            public IList GetStates()

            {

               var myResult = (from s in db.JobsJobProfiles.GroupBy(p => p.LocState)

                              orderby s.Key

                              select new StateResult

                              {

                               State = s.Key

                              }).ToList();        

                    return myResult;

             }

    StateResult class:

        public class StateResult

        {

            public string State { get; set; }

        }

    In my form I am trying to iterate through the result from GetStates() but I am not getting the correct information:

                foreach (var item in chk.GetStates())

                {

                    lstTestData.Items.Add(item.ToString());

                }

    I looks like what I am getting as data back is the route back to the StateResult class preperty, eg CrnWebsite.MyClass.StateResult.

    I cannot seen to get the "State" string text.

    Where am I going wrong here?

    Thanks

    Monday, September 24, 2012 9:15 PM
  • Hi uzzitt;

    // If GetStates returns a IList then you need to cast the object in IList to a StateResult.
    foreach (StateResult item in chk.GetStates())                  
    {  
        // You need to access the State Property of the StateResult object                                        
        lstTestData.Items.Add(item.State);
    }
    
    // If GetStates returns a List<StateResult> then you don't need to cast the object in List to a StateResult.
    foreach (var item in chk.GetStates())                  
    {  
        // You need to access the State Property of the StateResult object                                        
        lstTestData.Items.Add(item.State);
    }
    
    If you are using Windows form desktop application you do not have to iterate over the list and add to the control, you can do the following.
    lstTestData.DataSource = GetStates();
    lstTestData.DisplayMember = "State";

      


    Fernando (MCSD)

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

    Monday, September 24, 2012 10:48 PM
  • Hi Fernando,

    I am using web forms for website.

    for the last couple of days i have been trying

    foreach (var item in chk.GetStates())                 
    {  

       //I cannot get the item.State property for some reason here....
        lstTestData
    .Items.Add(item.State);
    }

    I tried the first approach..

    foreach (StateResult item in chk.GetStates())                 
    {  
        //I am able to get to the item.State property but I get a casting error here       
        lstTestData
    .Items.Add(item.State);
    }


    Monday, September 24, 2012 11:16 PM
  •   

    Please post the complete error you are getting and if it is happening at run time please post exception and inner exception if any.

      


    Fernando (MCSD)

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

    Tuesday, September 25, 2012 12:58 PM
  • Hi Fernando,

    I got it sorted. I cleaned up my code and built some basic pages and classes from scratch.

    I was able to use the:

    foreach (StateResult itemin chk.GetStates())                
    {  
        lstTestData
    .Items.Add(item.State);
    }

    I also had to clean up the group statement in the linq query as it was working fine when I created a temp list in code to query but then when I queried the db I got some errors.

    I was also looking at this link, but have not had time to go through and implemetn it to see if it would work for me:

    http://devtechnospot.wordpress.com/2011/11/07/return-anonymous-type-from-c-method/

    This grouping example also helped me:

    http://stackoverflow.com/questions/1634830/counting-items-in-grouped-results-in-linq-to-sql

    Many thanks for your help. I do understand it a bit more but need more flight time as I am new to Linq and very weak on it. I shall persevere.

    Thanks again,

    Regards.....



    • Marked as answer by uzzitt Tuesday, September 25, 2012 10:00 PM
    • Edited by uzzitt Tuesday, September 25, 2012 10:01 PM
    Tuesday, September 25, 2012 10:00 PM