Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How would I make this code more efficient using Linq


What I have tried:

 //Get all incidents
 List < DataRow > Incidents = rm.getData(Token, "incdet").Tables["Client Data"].AsEnumerable().ToList();

 //get incidents that fall between a date range
 var appointmentNoShow = from a in Incidents
                         where (Convert.ToDateTime(a["dateinc"].ToString()) >= firstDayOfMonth && Convert.ToDateTime(a["dateinc"].ToString()) <= lastDayOfMonth)
                         select a;

 //get all injuries
 List<DataRow> injuries = rm.getData(Token, "incemp").Tables["Client Data"].AsEnumerable().ToList();

 //put injuries that match incidents in date range into list
 var result = injuries.Where(p => Incidents.Any(p2 => p2["incid"].ToString() == p["incid"].ToString()));

// check if injuries have specific code add to list
 foreach (var item in result)
 {
     if (item["consqce"].ToString() == "107547" || item["consqce"].ToString() == "107548" || item["consqce"].ToString() == "107549")
     {
         IncidentRecord r = new IncidentRecord();
         r.ID = item["incid"].ToString();
         //r.Date = item["dateinc"].ToString();
         QualifyingList.Add(r);

     }

 }
 //select The incident that match the incident ids in the QualifyingList to get the dates
 var injuriesForMonth = Incidents.Where(p => QualifyingList.Any(p2 => p2.ID == p["incid"].ToString()));
Posted
Updated 12-Jan-17 8:29am
Comments
F-ES Sitecore 12-Jan-17 4:04am    
What do you mean by efficient? LINQ will make your code slower, so if by efficient you mean "faster" then I'd leave it as it is.

1 solution

Linq does not necessarily make anything more efficient: what it does is delays execution until the results are needed, which is a very different thing.

What I would suggest is that you use the Stopwatch class to find out where the bottlenecks in your code are, and look at ways in which that specific code can be improved. There isn't a "magic formula" to improve efficiency, and if there was, it certainly wouldn't be Linq - although Linq can do lazy evaluation and iteration skipping, manual code is frequently faster unless you know exactly what you are doing.
 
Share this answer
 
Comments
Jon McKee 12-Jan-17 4:17am    
Agreed! Though I would note PLINQ can help for certain situations if you really know what you're doing.

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