开发者

Problem with generic list and extension method(C#3.0)

I have an issue. I am making an extension class for a Collection and it is generic.. like

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;
        }
    }

But I cannot add items to t1 as it is declared null. Error: object reference not set to an instance of the object.

I am calling the method like

List<TestClass> listTC = new List<TestClass>();

            listTC.Add(new TestClass { Name = "Ishu", Age = 21 });
            listTC.Add(new TestClass { Name = "Vivek", Age = 40 });
            listTC.Add(new TestClass { Name = "some one else", Age = 12 });
            listTC.Search("Ishu");

And the test class is

public class TestClass
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

Using : (C#3.0) & Framework - 3.5 Thanks


As you probably don't want to manipulate (add, remove,...) the Search results after you performed a Search it is better practice to return IEnumerable<T> instead of ICollection<T>. Also C# has a special syntax for this: 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;
            }
        }
    }
}


Well what kind of collection do you want to use? You've got to have an actual collection to add your results to. List<T> is probably the simplest suggestion. Just change the first line of the method:

ICollection<T> t1 = new List<T>();

EDIT: Although this is the simplest change to the code, you should definitely consider using an iterator block as per Thomas's answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜