我需要创建一个方法,使用类型为T的通用枚举,它在我指定的术语中使用
public static object findInList<T>(T[] list, string searchTerm, string seachIndex)
{
string normalized1 = Regex.Replace(seachIndex, @"\s", "");
var sel = (from l in list
where normalized1.Equals([the item i want to compare])
select l).FirstOrDefault();
return sel ;
}
我需要这个,因为我想创建一个通用的方法来搜索我的数组中的项目,我可以用某种方式自定义(在原始方式的代码下面)
[...]
string normalized1 = Regex.Replace(seachIndex, @"\s", "");
sel = (from l in list
where normalized1.Equals(l.Ordine)
select l).FirstOrDefault();
[...]
[编辑] 感谢Servy的回答。对于这个答案的完整索引,我在这里添加如何调用此方法
Func<XXX, string> keySelector = delegate(XXX b) { return b.XX; };
var return = findInList<XXX>(list, keySelector, seachIndex);
其中XXX是列表的类型,XX是您要为搜索比较的属性
答案 0 :(得分:2)
这里需要的是你的方法接受一个选择器,一个函数决定你应该为每个对象比较什么。
public static T findInList<T>(
IEnumerable<T> sequence,
Func<T, string> keySelector,
string searchTerm,
string seachIndex)
{
string normalized1 = Regex.Replace(seachIndex, @"\s", "");
return (from l in sequence
where normalized1.Equals(keySelector(l))
select l).FirstOrDefault();
}
您还可以返回T
而不是object
,因为您知道它就是这样,确保调用者不需要将其转换回原来的状态。您可以接受IEnumerable
而不是数组,因为您只是迭代它,从而为调用者提供更大的灵活性,同时仍然允许您执行您需要执行的所有操作。