Rectangle 27 239

After calling GroupBy, you get a series of groups IEnumerable<Grouping>, where each Grouping itself exposes the Key used to create the group and also is an IEnumerable<T> of whatever items are in your original data set. You just have to call Count() on that Grouping to get the subtotal.

foreach(var line in data.GroupBy(info => info.metric)
                        .Select(group => new { 
                             Metric = group.Key, 
                             Count = group.Count() 
                        })
                        .OrderBy(x => x.Metric)
{
     Console.WriteLine("{0} {1}", line.Metric, line.Count);
}

I'm assuming you already have a list/array of some class that looks like

class UserInfo {
    string name;
    int metric;
    ..etc..
} 
...
List<UserInfo> data = ..... ;

When you do data.GroupBy(x => x.metric), it means "for each element x in the IEnumerable defined by data, calculate it's .metric, then group all the elements with the same metric into a Grouping and return an IEnumerable of all the resulting groups. Given your example data set of

<DATA>           | Grouping Key (x=>x.metric) |
joe  1 01/01/2011 5  | 1
jane 0 01/02/2011 9  | 0
john 2 01/03/2011 0  | 2
jim  3 01/04/2011 1  | 3
jean 1 01/05/2011 3  | 1
jill 2 01/06/2011 5  | 2
jeb  0 01/07/2011 3  | 0
jenn 0 01/08/2011 7  | 0

it would result in the following result after the groupby:

(Group 1): [joe  1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb  0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim  3 01/04/2011 1]

This was a brilliantly quick reply but I'm having a bit of an issue with the first line, specifically "data.groupby(info=>info.metric)". Plainly 'data' is the currently data set but what does 'info.metric' represet? the class definition?

"info.metric" would be the metric property/field on the UserInfo class you mentioned in your question.

Thanks figured that out but actually this appears to give me a single value - namely the total number of different metric counts. In this example I get "metrics 4" which indicates to me how many different counts I have.

Wow. You totally explained grouping!! That alone was worth the post.... i stil get the "metrics 4" result but thanks!

The start of this answer, "after calling GroupBy, you get a series of groups IEnumerable<Grouping>, where each Grouping itself exposes the Key used to create the group and also is an IEnumerable<T> of whatever items are in your original data set", is the clearest explanation of LINQ GroupBy I've yet read, thank you.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c# - linq with groupby and count - Stack Overflow

c# linq group-by
Rectangle 27 158

I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany to look at each item in each group.

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

The use of First() here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.

I'd also suggest that you should change the Quantity and Price properties to be int and decimal types respectively - why use a string property for data which is clearly not textual?

Ok my console app is working. Thanks for point me out to use First() and leave out SelectMany. The ResultLine is actually a ViewModel. The price will get formatted with currency sign. That's why I need it to be a string. But i could change quantity to int.. I'll see now if this may also help for my website. I'll let you know.

@ThdK: No, you should keep Price as a decimal too, and then change how you format it. Keep the data representation clean, and only change to a presentation view at the last possible moment.

Why not to Group by ProductCode and Name? Something like that: .GroupBy(l => new{l.ProductCode, l.Name}) and use ProductName = c.Key.Name,

Ok, it seems my collection was actually a wrapper around the real collection.. Shoot me.. Good thing is, I practiced some Linq today :)

c# - Linq: GroupBy, Sum and Count - Stack Overflow

c# .net linq
Rectangle 27 207

count(*)
count(column)

added this code so that people can run it

create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,null)

select count(*),count(id),count(id2)
from #bla

Just curious: if you have a row with all NULLs, would count(*) still count it, or is just count(column) for all columns?

It's worth mentioning that if you have a non-nullable column such as ID, then count(ID) will significantly improve performance over count(*).

@tsilb: The answer posted by @Alan states "count(*) is computed by looking at the indexes on the table in question rather than the actual data rows" which, if true, invalidates your comment. I appreciate that @Alan may be wrong but I'm interested in the source of your information in order to find out which is correct.

In SQL, what's the difference between count(column) and count(*)? - St...

sql
Rectangle 27 56

  • Use Count if you're using a list, since it knows it's size.
  • Use Length for an Array
  • If you just have an IEnumerable I would use .Any() over .Count() as it will be faster since it stops after checking one item.

c# - List Any or Count? - Stack Overflow

c# linq c#-4.0
Rectangle 27 52

  • Use Count if you're using a list, since it knows it's size.
  • Use Length for an Array
  • If you just have an IEnumerable I would use .Any() over .Count() as it will be faster since it stops after checking one item.

c# - List Any or Count? - Stack Overflow

c# linq c#-4.0
Rectangle 27 461

If you can't just limit the query itself with a where clause, you can use the fact that the count aggregate only counts the non-null values:

select count(case Position when 'Manager' then 1 else null end)
from ...

You can also use the sum aggregate in a similar way:

select sum(case Position when 'Manager' then 1 else 0 end)
from ...

what if my field is integer and I want to match null. it doesn't work this way select count(case IntegerField when 'NULL' then 1 else null end) from

null
case when IntegerField is null then ...

When working with boolean fields you can use this : SUM(CONVERT(int, IsManager))

sql - Is it possible to specify condition in Count()? - Stack Overflow

sql sql-server tsql
Rectangle 27 187

Assuming you do not want to restrict the rows that are returned because you are aggregating other values as well, you can do it like this:

Let's say within the same column you had values of Manager, Supervisor, and Team Lead, you could get the counts of each like this:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount,
    count(case when Position = 'Supervisor' then 1 else null end) as SupervisorCount,
    count(case when Position = 'Team Lead' then 1 else null end) as TeamLeadCount,
from ...

Why the downvotes? A comment would be helpful.

@RedFilter It's not even necessary to specify the else part, just end it right after the 1.

@Denis: correct - I often leave the else in as it better documents the results of the case statement, especially for novie SQL developers. For brevity, it can be removed in this case.

sql - Is it possible to specify condition in Count()? - Stack Overflow

sql sql-server tsql
Rectangle 27 177

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.ParentId into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t=>t.ChildId != null) }

OK, that works, but why? How do you think through it? How does not counting null values give us the same as COUNT(c.ChildId)? Thanks.

This is how SQL works. COUNT(fieldname) will count the rows in that field that are not null. Maybe I don't get your question, please clarify if that's the case.

I guess I always thought about it in terms of counting rows, but you are correct, only the non-null values are counted. Thanks.

.Count() will generate COUNT(*) which will count all the rows in that group, by the way.

c# - LINQ - Left Join, Group By, and Count - Stack Overflow

c# .net linq linq-to-sql
Rectangle 27 23

userInfoList
List<UserInfo>
var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

c# - linq with groupby and count - Stack Overflow

c# linq group-by
Rectangle 27 22

>>> L = [[1, 2, 3], [1, 1, 1]]
>>> sum(x.count(1) for x in L)
4

This won't work with arbitrary nesting. - 1

@RestRisiko: Where does the question say arbitrary nesting is required? Your own answer on this question doesn't even cover that, yet you'll downvote others for it?

Why are people downvoting very valid answers. I gave a +1 for this and like it better than my answer. But my answer was not crappy, and definitely, this one is not!!!

@manojlds, @Thomas: Don't bother about trolls. This is a perfectly valid answer given the OP's requirement.

python - Nested List and count() - Stack Overflow

python list
Rectangle 27 17

Any just checks if the sequence contains at least one element, while Count needs to iterate over all elements. That's the difference. A classic scenario where Any is preferred over Count is this:

if (sec.Count() > 0)
if (sec.Any())

And imagine what happens if you try to Count an infinite sequence...

@Claudio , is it just the use of Any ? what about the overloaded ?

Same for the overloads, Any stops as soon as it finds the first element satisfying the predicate, while Count has to scan the whole sequence (potentially infinite, as already said).

c# - Why should I use Any method instead of Count? - Stack Overflow

c# asp.net linq entity-framework linq-to-entities
Rectangle 27 17

Any just checks if the sequence contains at least one element, while Count needs to iterate over all elements. That's the difference. A classic scenario where Any is preferred over Count is this:

if (sec.Count() > 0)
if (sec.Any())

And imagine what happens if you try to Count an infinite sequence...

@Claudio , is it just the use of Any ? what about the overloaded ?

Same for the overloads, Any stops as soon as it finds the first element satisfying the predicate, while Count has to scan the whole sequence (potentially infinite, as already said).

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c# - Why should I use Any method instead of Count? - Stack Overflow

c# asp.net linq entity-framework linq-to-entities
Rectangle 27 15

There are a few possible problems related to this. One of them is that if the link is shortened, Twitter won't add it up unless you add the "counturl" url property.

Also, Twitter doesn't count the tweets coming from protected accounts (accounts that don't share their tweets).

Please let me know if none of this offers the solution.

I tried it with data-counturl on whattheplace.com/static/tweetbutton.html (the two buttons at the bottom) with the non-protected Twitter account @chrism_test but it still didn't work. :-(

Twitter Tweet Button does not count - Stack Overflow

twitter
Rectangle 27 12

You can wrap your query inside another one:

SELECT
    cnt      AS page_visits
  , COUNT(*) AS number_of_visitors
FROM
    ( SELECT 
          COUNT(*) AS cnt                --- use: COUNT(DISTINCT page_id)
                                         --- for a different count
      FROM vislog 
      GROUP BY visid
   ) AS grp
GROUP BY cnt 
ORDER BY number_of_visitors ;

or (I suppose this makes more sense for passing the numbers to a chart), remove the ORDER BY which is the same as putting:

ORDER BY cnt ;

php - MYSQL count of count? - Stack Overflow

php mysql sql aggregation
Rectangle 27 13

The following query works. It uses each group to do the select instead of SelectMany. SelectMany works on each element from each collection. For example, in your query you have a result of 2 collections. SelectMany gets all the results, a total of 3, instead of each collection. The following code works on each IGrouping in the select portion to get your aggregate operations working correctly.

var results = from line in Lines
              group line by line.ProductCode into g
              select new ResultLine {
                ProductName = g.First().Name,
                Price = g.Sum(_ => _.Price).ToString(),
                Quantity = g.Count().ToString(),
              };

c# - Linq: GroupBy, Sum and Count - Stack Overflow

c# .net linq
Rectangle 27 13

Something else to bear in mind is that the tweet counts are not accurate in real time. They are cached and updated asynchronously. See http://dev.twitter.com/pages/tweet_button_faq#count-api-increment

Twitter Tweet Button does not count - Stack Overflow

twitter
Rectangle 27 53

Consider using a subquery:

If the query types are connected by an association, this simplifies to:

from p in context.ParentTable 
let cCount = p.Children.Count()
select new { ParentId = p.Key, Count = cCount } ;

If I remember correctly (it's been a while), that query was a simplified version of a large one. If all I needed was the key and count your solution would've been cleaner / better.

Your comment doesn't make sense in context with original question and upvoted answers. Additionally - if you want more than the key, you have the whole parent row to draw from.

this help me with a somewhat related problem, thanks

c# - LINQ - Left Join, Group By, and Count - Stack Overflow

c# .net linq linq-to-sql
Rectangle 27 33

Another minor difference, between using * and a specific column, is that in the column case you can add the keyword DISTINCT, and restrict the count to distinct values:

select column_a, count(distinct column_b)
from table
group by column_a
having count(distinct column_b) > 1;

Should the group by column and the one being counted be different? otherwise you would get nothing from this query

Yes, sorry.. I hadn't noticed that they were the same column in the example. I'll update the post.

In SQL, what's the difference between count(column) and count(*)? - St...

sql
Rectangle 27 11

userInfos.GroupBy(userInfo => userInfo.metric)
        .OrderBy(group => group.Key)
        .Select(group => Tuple.Create(group.key, group.Count()));

c# - linq with groupby and count - Stack Overflow

c# linq group-by
Rectangle 27 9

Here is yet another approach to flatten a nested sequence. Once the sequence is flattened it is an easy check to find count of items.

def flatten(seq,container=None):
    if container is None:
        container = []
    for s in seq:
        if hasattr(s,'__iter__'):
            flatten(s,container)
        else:
            container.append(s)
    return container


c = flatten([(1,2),(3,4),(5,[6,7,['a','b']]),['c','d',('e',['f','g','h'])]])
print c
print c.count('g')

d = flatten([[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]])
print d
print d.count(1)

The above code prints:

[1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
1
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
12

python - Nested List and count() - Stack Overflow

python list