我需要搜索 dblinq 表,以便该函数在任何字段与搜索输入匹配时返回行列表。
它更类似于 google 搜索,您可以在其中搜索任何关键字并显示匹配的文档列表。
我在这项技术中使用了反射。能否请您检查此方法是否正确,或者是否有任何简单的方法可以实现此目的?
我已经得到了 dblinq 表行的所有属性,并比较了它的字符串类型,然后检查了值。
我用过的代码
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 am getting expected output from this method but I would like to know if I have any alternative way too.
最佳答案
我手头没有 Visual Studio 来测试它,但这应该也可以:
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
我只会获取属性一次,因为每次都相同。
关于你是否使用反射的问题......这取决于。
如果您的 Contact
类型只有少数 (2-5) 个字符串属性,我将手动实现此方法而不是使用反射。它可能有点乏味,但在可读性、速度(但不应该有显着差异)方面付出了代价,并且您可以控制比较哪些属性(也许您的联系人包含不应搜索的字符串属性)。
如果您计划扩展/更改 Contact
类型或必须检查大量属性,我会使用反射。
关于c# - 如何使用 linq 从表中搜索任何属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6824291/