views:

515

answers:

6

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<>?

+3  A: 

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);
        }
    }
Daok
use anonymous delegates, this isn't .NET 1.1
FlySwat
He said c# version 2.0 no 1.1???
Daok
Nice this is working . Thank you sir. I have now a method that take this Predicate object from list object.
SexyBunny
My point, was show him how to do it using anonymous delegates, not using a named delegate (ala .net 1.1 style) Kent's method above does the same thing in a much more concise manner.
FlySwat
+1 for the Jon Skeet reference ;-) Nice samples there, wish all answers had good samples!
Erik van Brakel
Kent code is ok but my code let the programmer having the Predicate somewhere else in the code. SexyBunny wrote in comment that he use is in a method now, so he can use it has parameters and change it on the fly if he/she wants. I think My sample is perfect to show him the possibilities of Predicate
Daok
+8  A: 

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

HTH, Kent

Kent Boogaart
A: 

Unfortunately the List data structure requires iteration to find data (note that the FindAll methods above will iterate your collection under the covers - just in case you were trying to avoid that at all costs), unless you know the index of that data then you can do this:

List<String> list = new List<String>();
list.Add("andrew");
list.Add("nicole");

String value = list[1]; // returns "nicole"
Andrew Hare
+2  A: 

Without LINQ, your main option is to do looping and comparison on each element of the list. There are a few methods that might help you though.

List<T>.FindAll() takes a Predicate delegate and will return all items that match the condition. List<T>.CopyTo() and List<T>.GetRange() let you extract a range of elements. Other than that, you really can't do much in the way of specific selection outside of LINQ.

OwenP
+1  A: 

The truth is, even if you do end up using Predicates through Find or FindAll, all it's doing internally is looping through the list, and running your Predicate to test for a match. Performance wise you're not gaining anything, but it definitely makes for neater code.

BFree
LINQ does the same thing.
FlySwat
LINQ does it with lazy evaluation though - an important distinction for memory usage.
TheSoftwareJedi
A: 

I think most of the answers above are all just providing alternative ways of doing exactly what you're trying to avoid. Given the data structure, no matter what implementation you choose, you/it will have to compare every item and pick out those that match.

Depending on your matching criteria, a SortedList may help you avoid searching the whole list for every query. If your list contains objects you've created, overriding GetHashCode and Equals will help you out.

If you matching criteria is fairly complex, you may need a different data structure altogether, like a trie for strings.

Austin Salonen