Click here to Skip to main content
15,887,854 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to search the name of the students which contains the keywords,at first I pass the keywords separated by commas,but I find the search time is too long.But when I convert these keywords into an array,it is real fast.Why do linq search has a huge difference in efficiency?Is that because of the array or linq?
C#
**Using string to search**

    var keyWord="Lyly,Tom,Jack,Rose"; //and so on,more than 500 names
    var student= Context.Students.Where(i => keyWord.Contains(i.Name));//very slow

**Using array to search**

    var keyWord="Lyly,Tom,Jack,Rose"; //and so on,more than 500 names
     var keyWordArray=keyWord.split(',');
    var student= Context.Students.Where(i => keyWordArray.Contains(i.Name));//fast
Posted
Updated 12-Nov-14 3:34am
v2

1 solution

Because searching a string is inefficient and should be avoided.
Now take that array and populate a HashSet and you should see even better performance over searching the array.

Furthermore, the string search can return false positives -- try searching "Bob,Robert,Mary" for "Rob".

Another benefit of the HashSet is that you can tell it to use a case-insensitive comparer.
 
Share this answer
 
v3
Comments
BillWoodruff 12-Nov-14 9:47am    
As long as there are no duplicate strings to be stored ?
PIEBALDconsult 12-Nov-14 9:54am    
Even better then, duplicates "Bob,Bob,Bill,Bob,Mary,Bill,Tom" would cause even worse string and array performance.
BillWoodruff 12-Nov-14 10:50am    
... mmm ... I was thinking of the case where there would be a reason to have duplicate values. But, I forget what that was :)
Matt T Heffron 12-Nov-14 12:40pm    
In that case, the better data structure would be Dictionary<string, List<something-to-distinguish-actual-values>>
Or a real DB...
PIEBALDconsult 12-Nov-14 12:45pm    
Or a class with a custom GetHashCode or comparer that takes that into account.

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