Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of trues in a table in LINQ to SQL

I have a table like this

 StudID   Date      I  II  III  IV   V   VI   VII  VIII 
-------------------------------------------------------------- 
  100    2-10-11    T   T   F    F   F   F     F     T
  101    2-10-11    T   T   T    F   F   F     F     T
  100    3-10-11    T   F   F    F   F   F     F     T
  100    4-10-11    T   F   F    F   F   F     F     T

Now i need to get the number of T's i.e, Trues in the table for a particular student in a particular month StudID is a varchar field Date is a datetime field and all the other datatype with bit

any ideas?

like image 998
diamond Avatar asked Dec 22 '22 12:12

diamond


2 Answers

As the comments suggest, you should normalize your data.

However if you are unable to do that, you simply need to count the number of trues in each row.

context.Studs.Sum(s => (s.I ? 1 : 0) + (s.II ? 1 : 0) + ... + (s.VIII ? 1 : 0));

edit: To restrict the sum based on StudID and the month, you would use a Where operator

var id = "100";
var month = 10;

var set = context.Studs.Where(s => s.StudID == id;
set = set.Where(s => s.Date.Month == month);

return set.Sum(s => (s.I ? 1 : 0) + (s.II ? 1 : 0) + ... + (s.VIII ? 1 : 0));
like image 61
Kirk Broadhurst Avatar answered Dec 27 '22 09:12

Kirk Broadhurst


var numberOfTrues = context.Students.
Where(x => x.StudID == 123 && x.Date.Month == studentMonth).
Sum(x => x.I.ToInt() + x.II.ToInt() + ... + x.VIII.ToInt());


// Add extension method    
public static int ToInt(this bool value)
{
   return value ? 1 : 0;
}
like image 25
Vlad Bezden Avatar answered Dec 27 '22 11:12

Vlad Bezden