Skip to content
Advertisement

How can I count total item in an object/record and count only the value = true

var obj = (from r in db.Module_Completion
                  .Where(r => r.star_id == User.Identity.Name)
                 
                   select new 
                   {
                         r.adv_stud_success,
                         r.important_policies,
                         r.technology,
                         r.finances,
                         r.resources,
                         r.student_life,
                         r.next_steps
                   }).FirstOrDefault();

obj = {true, false, false , true,…}; This is only one record that I query from database by using Linq

The reason is I would like to display Finsished 2 of 7 , that is why I need to count items in a record. Thank you in advance!

 public partial class Module_Completion
{
    public int module_completionId { get; set; }

    [StringLength(10)]
    public string star_id { get; set; }

    public bool adv_stud_success { get; set; }

    public bool important_policies { get; set; }

    public bool technology { get; set; }

    public bool finances { get; set; }

    public bool resources { get; set; }

    public bool student_life { get; set; }

    public bool next_steps { get; set; }
}

After I can store numbers in variable, then I would like to display like this”Finished 2 of 7″

Advertisement

Answer

My solution involves 2 parts first. Create a ViewModel to get the number of completed object that associates with the class that goes:

public class ModuleCompletesVM
{
    public Module_Completion Module_Completion { get; set; }
    public int Completed { get

        {
            return (Convert.ToInt32(Module_Completion.stud_success) + 
                    Convert.ToInt32(Module_Completion.important_policies) + 
                    Convert.ToInt32(Module_Completion.technology) + 
                    Convert.ToInt32(Module_Completion.finances) +
                    Convert.ToInt32(Module_Completion.resources) + 
                    Convert.ToInt32(Module_Completion.next_steps) + 
                    Convert.ToInt32(Module_Completion.student_life));
        }
    }
}

Note that this View Model would calculate the number of completed subject of each Module_Completion Class and then from your controller. You just need to do something like this

var model= from s in db.Module_Completion
                   select new ModuleCompletesVM
                   {
                       Module_Completion = s
                   };
        

You can also achieve this by creating a function in SQL database as well. Another piece of advice is that, do consider stop using underscrore in your data table and data field. Follow the latest convention, the next person who take over your code will appreciate that.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement