Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Consider following table structure
PartID PartInstanceID PartInstanceName Used
1 1 A Y
1 2 B N
1 3 C N
1 4 D N
2 5 E N
2 6 F N
3 7 G Y
4 8 H N
5 9 I N
5 10 J N


Can anyone tell me a query in LINQ to get following output?

To get Unused instances:
PartID InstanceCount
1 3
2 2
3 0
4 1
5 2

To get used instances:
PartID InstanceCount
1 1
2 0
3 1
4 0
5 0

Please let me know.

Thanks in advance.
Posted

C#
var query = from p in myTable
            where p.Used = "N"
            group p by p.PartID into gp
            select new
                   {
                       PartID = gp.PartID,
                       InstanceCount = gp.Count(),
                   }


I'll leave it to you to alter the above to get the result for unused parts.
 
Share this answer
 
v2
Comments
Amol_27101982, India 14-Oct-11 7:54am    
It works dude :)

Thanks a lot.
Simon Bang Terkildsen 14-Oct-11 8:26am    
My pleasure
sowjanya bantupalli 4-Sep-15 2:51am    
sorry to say this i didnt get result through this query pls check my query once
var x = from u in db.Appointment.AsEnumerable () where u.VisitingDepartmentName!=null group u by u.VisitingDepartmentName
into g select new { VisitingDepartmentName = g.Key ,
TotalNoofVisitors = g.Count(),
//TotalNoofVisitors=g==null ? 0:g.Count(),
Records = g
};
inresult count is zero it gives like this
This is very simple. Have a look with this

C#
var counts = products.GroupBy(l => l.PartID).Select(lg => new { PartID = lg.Key, InstanceCount = lg.Count() });    


Here products is a list object. you might think that the collection of your data in a List.
 
Share this answer
 
Comments
Amol_27101982, India 14-Oct-11 7:56am    
Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900