Accessing a List multiple times in same code block – Any better approach?

  • A+

I need to set the values of multiple labels from a single list based on different conditions. Here is my code:

List<RFPModel> lst = RFPModel.GetAll();  //ALL if(lst.Count>0) {     lblActive.InnerText = lst.Count(a => a.StatusID == (int)ProjectStatus.Project_Active).ToString();     lblCompleted.InnerText = lst.Count(a => a.StatusID == (int)ProjectStatus.Project_Completed).ToString();     lblProposal.InnerText = lst.Count(a => a.StatusID == (int)ProjectStatus.Proposal_UnderProcess).ToString();     lblProposalsRej.InnerText = lst.Count(a => a.StatusID == (int)ProjectStatus.Proposal_Rejected).ToString();     lblRFPRec.InnerText= lst.Count(a => a.StatusID == (int)ProjectStatus.RFP_Submitted).ToString();     lblRFPRef.InnerText= lst.Count(a => a.StatusID == (int)ProjectStatus.RFP_Rejected).ToString();     lblRFPApp.InnerText = lst.Count(a => a.StatusID == (int)ProjectStatus.RFP_Approved).ToString(); } 

I am afraid that this approach may affect the performance as everytime you need a value you traverse the list. Any suggestion for the better approach will be highly appreciated.


Use a GroupBy (preferably at the db IQueryable level), then for extra flavor you can to ToDictionary to make the look up more efficient

var dict = lst.GroupBy(x => x.StatusID)              .Select(x => new { x.Key, count = x.Count() })              .ToDictionary(x => (ProjectStatus)x.Key, x => x.count.ToString());  lblActive.InnerText  = dict[ProjectStatus.Project_Active]; lblCompleted.InnerText  = dict[ProjectStatus.Project_Completed]; ... 

The assumption is the StatusID maps one to one with ProjectStatus

Note the additional Select, is superfluous however is added for in-case you just wanted a list

Additional Resources

Enumerable.GroupBy Method

Groups the elements of a sequence.

Enumerable.Select Method

Projects each element of a sequence into a new form.

Enumerable.ToDictionary Method

Creates a Dictionary from an IEnumerable.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: