Question

I have a LINQ statement like below:

var pairs = new [] { 
    new { id = 1, name = "ram", dept = "IT", sal = "3000" }, 
    new { id = 2, name = "ramesh", dept = "IT", sal = "5000" }, 
    new { id = 3, name = "rahesh", dept = "NONIT", sal = "2000" },
    new { id = 5, name = "rash", dept = "NONIT", sal = "7000" }
};
var query = (from dynamic stud in pairs
             group stud by stud.dept into grps
             select new { 
                 IT = grps.Count(stud => stud.dept == "IT"), 
                 NONIT = grps.Count(stud => stud.dept == "NONIT") 
             });

Here I am getting the IT and NONIT count, but I am getting two rows of results and each group is querying separately. Can I count both of them at a single go? The output I am getting here if I for-loop the query like below is 2,0 and 0,2

foreach (dynamic result in query)
{
    Console.WriteLine(result.IT + "," + result.NONIT);
}

This is because each group is querying separately. I am looking for a result like 2,2. Is this possible?

Was it helpful?

Solution

In case you know exactly that department names is either "IT" or "NONIT", and the result should be single data, you can get the expected output without grouping :

var result2 = new
              {
                  IT = (from dynamic stud in pairs where stud.dept == "IT" select stud).Count(),
                  NONIT = (from dynamic stud in pairs where stud.dept == "NONIT" select stud).Count()
              };
Console.WriteLine(result.IT + "," + result.NONIT);

or if you favor grouping, I suggest to convert query result to dictionary to easily lookup count by department name :

var query = (from dynamic stud in pairs
              group stud by stud.dept
              into grps
              select
                  new
                  {
                      Dept = grps.Key,
                      Count = grps.Count()
                  }).ToDictionary(o => o.Dept, o => o.Count);

Console.WriteLine(string.Format("result : {0}", query["IT"] + "," + query["NONIT"]));

If none of above suits your requirement, please update the question to explain more about what you're trying to achieve exactly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top