Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do get some of the object from a list without Linq?

I am running C# framework 2.0 and I would like to get some of the data from a list? The list is a List<>. How can I do that without looping and doing comparaison manually on each element of the List<>?

like image 648
SexyBunny Avatar asked Dec 07 '22 08:12

SexyBunny


2 Answers

If I follow your question correctly, you can just call the Find() or FindAll() methods to get data items out of the list. For example:

List<string> myList = ..;
List<string> startingWithA = myList.FindAll(delegate(string s) { return s.StartsWith("A"); });
like image 101
Kent Boogaart Avatar answered Dec 09 '22 21:12

Kent Boogaart


You can try Predicate. Here is a code I wrote to illustrate the point. Of course, as you can see in this example, you can move the Predicate outside the calling class and have a control on it. This is useful if you need to have more option with it. Inside the predicate you can do many comparison with all property/function of your object.

   static void Main()
    {
        List<SimpleObject> list = new List<SimpleObject>();
        list.Add(new SimpleObject(1,"Jon"));
        list.Add(new SimpleObject( 2,  "Mr Skeet" ));
        list.Add(new SimpleObject( 3,"Miss Skeet" ));
        Predicate<SimpleObject> yourFilterCriteria = delegate(SimpleObject simpleObject)
        {
            return simpleObject.Name.Contains("Skeet");
        };
        list = list.FindAll(yourFilterCriteria);//Get only name that has Skeet : Here is the magic
        foreach (SimpleObject o in list)
        {
            Console.WriteLine(o);
        }
        Console.Read();
    }
    public class SimpleObject
    {
        public int Id;
        public string Name;

        public SimpleObject(int id, string name)
        {
            this.Id=id;
            this.Name=name;
        }

        public override string ToString()
        {
            return string.Format("{0} : {1}",Id, Name);
        }
    }
like image 30
Patrick Desjardins Avatar answered Dec 09 '22 20:12

Patrick Desjardins