Thursday, April 21, 2011

having and conditional count() in linq query

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?)
From stackoverflow
  • 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)

    Rodniko : Thank you very much, i need the result as IQueryable, Is there a way to create the 'select' result as a IQueryable? or do i need to create the rows manually?
    Thomas Levesque : see updated answer
    Rodniko : Thank you very much :)
  • Thanks! it helped me a lot.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.