C# 3.0 通用列表和扩展方法(C#3.0)存在问题

C# 3.0 通用列表和扩展方法(C#3.0)存在问题,c#-3.0,C# 3.0,我有个问题。我正在为一个集合创建一个扩展类,它是泛型的。。像 public static class ListExtensions { public static ICollection<T> Search<T>(this ICollection<T> collection, string stringToSearch) { ICollection<T> t1=null;

我有个问题。我正在为一个集合创建一个扩展类,它是泛型的。。像

public static class ListExtensions
    {

        public static ICollection<T> Search<T>(this ICollection<T> collection, string stringToSearch)
        {
            ICollection<T> t1=null;           

            foreach (T t in collection)
            {
                Type k = t.GetType();
                PropertyInfo pi = k.GetProperty("Name");
                if (pi.GetValue(t,null).Equals(stringToSearch))
                {
                    t1.Add(t);
                }
            }
            return t1;
        }
    }
使用:(C#3.0)和框架-3.5
谢谢

那么你想用什么样的收藏品呢?你必须有一个实际的集合来添加你的结果<代码>列表可能是最简单的建议。只需更改方法的第一行:

ICollection<T> t1 = new List<T>();
ICollection t1=新列表();

编辑:虽然这是对代码的最简单的更改,但是您应该根据托马斯的回答明确地考虑使用迭代器块。

< P>因为您可能不想操作(添加、删除、……)执行
搜索后的搜索结果
最好返回
IEnumerable
,而不是
ICollection
。C#还有一种特殊的语法:
yield

public static class ListExtensions
{
    public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch)
    {
        foreach (T t in collection)
        {
            Type k = t.GetType();
            PropertyInfo pi = k.GetProperty("Name");
            if (pi.GetValue(t,null).Equals(stringToSearch))
            {
                yield return t;
            }
        }
    }
}
公共静态类ListExtensions
{
公共静态IEnumerable搜索(此ICollection集合,字符串stringToSearch)
{
foreach(集合中的T)
{
类型k=t.GetType();
PropertyInfo pi=k.GetProperty(“名称”);
if(pi.GetValue(t,null).Equals(stringToSearch))
{
收益率t;
}
}
}
}

Sir。。还有一件事。在实现该方法以获取过滤列表之后,我正在编写代码列表newlistc=listc.Search(“Ishu”).ToList();如果不声明额外的newlistTC,我就无法返回新的收集结果。先生。。还有一件事。在实现该方法以获取过滤列表之后,我正在编写代码列表newlistc=listc.Search(“Ishu”).ToList();如果不声明额外的newlistTC,我就不能返回新的收集结果吗
ICollection<T> t1 = new List<T>();
public static class ListExtensions
{
    public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch)
    {
        foreach (T t in collection)
        {
            Type k = t.GetType();
            PropertyInfo pi = k.GetProperty("Name");
            if (pi.GetValue(t,null).Equals(stringToSearch))
            {
                yield return t;
            }
        }
    }
}