简体   繁体   中英

how to implement group by in linq query?

i have implemented group by query like

var query = (from a in Main
             group a by a.Parent into g
             where g.Count() >= 0
             select new
             {
                 parent= g.Key,
                 Name= g.Select(y => y.name).Count(),
                 Contact= g.Select(x => x.contact).Count(),
                 Friends= g.Select(z => z.friends).Count(),
             }).ToArray();

where as in the Main am getting the records like

In first list  ====>      Parent="1"
                          name="2"
                          contact=0
                          friends=0 

In second List ===>       Parent="2"
                          name="2"
                          contact=0
                          Friends=0        

But when i am using the group by query i am getting values in this way

parent="1",Name="2",Contact="2",Friends="2" 

parent="2",Name="3",Contact="2",Friends="2"

And also i need the count of each field.

so please can you tell where i have done wrong,

Thanks in Advance.

First of all, don't use ToArray() after grouping and expect the same thing.

When you are doing the regular Select-Where query what that will return is an IEnumerable that you transform to an array

The difference when you do a group by is that the return type will be IGrouping which will not translate to the same array you are expecting it to.

You need to handle the output differently if grouping.


Suggestion:

int nameCount = 0;
int contactCount = 0;
int friendCount = 0;

Main.GroupBy(x => x.Parent).ToDictionary(pair => pair.Key, pair => {
   nameCount += pair.Count(y => y.Name);
  //etc. for the rest of the counters.
}

This way, the selector function that iterates through elements of the grouping will be used to sum up the contacts, friends and names of each element. I hope i understood the context of your question.

g.Select(x => x.friends).Count(),

You may be confusing the meaning of the Count operator. Count computes the number of elements projected by the query, not their aggregate sum. Thus, if g contains 2 elements, then g.Select(x => x.anything) will always return 2, irrespective of the values of the anything property.

I assume that you mean to return the sum of the values projected from the friends property, in which case, you should use:

g.Sum(x => x.friends),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM