Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于在可枚举项中查找的LINQ泛型函数_C#_Linq - Fatal编程技术网

C# 用于在可枚举项中查找的LINQ泛型函数

C# 用于在可枚举项中查找的LINQ泛型函数,c#,linq,C#,Linq,我需要创建一个方法,该方法使用一个类型为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 n

我需要创建一个方法,该方法使用一个类型为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 ;
}
[编辑] 谢谢Servy的回答。对于这个答案的完整索引,我在这里添加了如何调用这个方法

Func<XXX, string> keySelector = delegate(XXX b) { return b.XX; };
var return = findInList<XXX>(list, keySelector, seachIndex);
Func keySelector=delegate(XXX b){return b.XX;};
var return=findInList(list、keySelector、seachIndex);

其中XXX是列表的类型,XX是您要为搜索比较的属性

这里您需要的是让您的方法接受一个选择器,一个确定您应该为每个对象比较什么的函数

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();
}
publicstatict findInList(
可数序列,
Func键选择器,
字符串搜索项,
字符串seachIndex)
{
字符串normalized1=Regex.Replace(seachIndex,@“\s”,“”);
返回(按顺序从l开始)
其中normalized1.Equals(keySelector(l))
选择l).FirstOrDefault();
}

您还可以返回一个
T
,而不是
对象,因为您知道它是什么,确保调用者不需要将它转换回原来的状态。你可以接受一个
IEnumerable
而不是数组,因为你只需要对它进行迭代,这样就给了调用方更多的灵活性,同时还可以让你做所有你需要做的事情。

在你传入委托的地方添加第四个参数怎么样?我不明白你需要什么,我如何用Func调用这个方法?你能给我举个例子吗?传入一个接受序列中类型的对象并返回字符串的方法。如果你愿意,你可以使用lambda,尽管你不必这样做。您可以在lambda的文档中查找大量示例。@Servy看起来OP想要进行搜索和替换。在这种情况下,您需要使用
表达式
,然后将其转换为
属性信息
,这样您就可以同时获得属性的
get
set
,然后调用
get
replace
然后
set
@Aron他只使用replace来删除搜索文本中的空格。看起来他只是在寻找与搜索文本匹配的第一个项目。
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();
}