How to search for any property from a table with linq?

I need to find the dblinq table so that the function returns a list of strings if any of the fields matches the search input.

This is more like a google search where you look at any keyword and a list of related documents is displayed.

I used reflection for this technique. Can you check if this method is correct, or is there any simple way to achieve this?

I have all the row properties of a dblinq table and compares if its the row type, and then checked the value.

The code I used

public static List<Contacts> SearchContact(string searchText) { List<Contacts> list = new List<Contacts>(); try { var rows= from p in context.tblContacts select p; foreach (var contact in rows) { Type type = contact.GetType(); Type typesearch = searchText.GetType(); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo pro in properties) { if (pro.PropertyType == typesearch) { var value = pro.GetValue(contact, null); string val = value as string; if (val != null && val == searchText) { list.Add(contact); break; } } } } } catch (Exception ex) { } return list; } 

PS: I get the expected result from this method, but I would like to know if I have an alternative way.

+6
source share
2 answers

I don't have Visual Studio manually to test it, but this should work too:

 var contactProperties = typeof(Contact).GetProperties() .Where(x => x.PropertyType == typeof(string)) .ToArray(); from contact in context.tblContacts from property in contactProperties let value = property.GetValue(contact, null) as string where value == searchText select contact 

I would get the properties only once, because it is the same every time.

To your question whether to use reflection or not .. it depends. If your Contact type has only a few (2-5) string properties, I would use this method manually instead of using reflection. It may be a bit tedious, but it pays for readability, speed (but there shouldn't be any noticeable difference), and you can control which properties are compared (maybe your Contact contains a string property that you don’t need to look for).

If you plan to extend / change the Contact type or you need to check a large piece of properties, I would go with a reflection.

+2
source
 public static List<Contacts> SearchContact(string searchText) { return (from contact in context.tblContacts let type = contact.GetType() let typesearch = searchText.GetType() let properties = type.GetProperties() where (from pro in properties where pro.PropertyType == typesearch select pro.GetValue(contact, null) into value select value as string).Any(val => val != null && val == searchText) select contact).ToList(); } 

EDIT: The exception handling part is missing, but it's easy to enable.

0
source

Source: https://habr.com/ru/post/893543/


All Articles