Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

having and conditional count() in linq query

Tags:

syntax

linq

I want to create this query:

select Something, count(Something) as "Num_Of_Times"
from tbl_results
group by Something
having count(Something)>5

I started with this:

tempResults.GroupBy(dataRow => dataRow.Field<string>("Something"))
   .Count() //(.......what comes here , to make Count()>5?)
like image 494
Rodniko Avatar asked Aug 26 '09 08:08

Rodniko


People also ask

How do you write a count query in Linq?

Count() methodIEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count(); NOTE: The Count() LINQ method (an extension method to IEnumerable<T> ) is slightly different from the Count property on List<T> .

Can we use multiple where clause in LINQ query?

A single query expression may have multiple where clauses.

What is any () in Linq?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

Which clause is used for conditions in Linq?

In LINQ, we can use Where() clause in the query to define multiple conditions, as shown below. This is how we can use LINQ where clause filtering operator to filter data based on conditions.


1 Answers

from item in tbl_results
group item by item.Something into groupedItems
let count = groupedItems.Count()
where count > 5
select new { Something = groupedItems.Key, Num_Of_Times = count };

UPDATE : This would give you the result as an IQueryable<DataRow> :

DataTable dt= new DataTable();
dt.Columns.Add("Something", typeof(int));
dt.Columns.Add("Num_Of_Times", typeof(int));

var results =   (from item in tbl_results
                 group item by item.Something into groupedItems
                 let count = groupedItems.Count()
                 where count > 2
                 select dt.Rows.Add(groupedItems.Key, count)).AsQueryable();

(note that it also fills the dt table)

like image 143
Thomas Levesque Avatar answered Sep 19 '22 03:09

Thomas Levesque