tags:

views:

240

answers:

5

What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern.

Currently I use code like this:

// mObjList is a List<MyObject>
MyObject match = null;
foreach (MyObject mo in mObjList)
{
    if (Criteria(mo))
    {
        match = mo;
        break;
    }
}

or

// mObjList is a List<MyObject>
bool foundIt = false;
foreach (MyObject mo in mObjList)
{
    if (Criteria(mo))
    {
        foundIt = true;
        break;
    }
}
+1  A: 

Put the code in a method and you save a temporary and a break (and you recycle code, as a bonus):

T Find<T>(IEnumerable<T> items, Predicate<T> p) {
    foreach (T item in items)
        if (p(item))
            return item;

    return null;
}

… but of course this method already exists anyway for Lists, even in .NET 2.0.

Konrad Rudolph
A: 

@ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber. Presumably

mObjList.Find(...
Nick
+8  A: 

@ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber.

In C# 2.0 you'd write:

result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; });

3.0 knows lambdas:

result = mObjList.Find(x => x.ID == magicNumber);
Konrad Rudolph
+2  A: 

Using a Lambda expression:

List<MyObject> list = new List<MyObject>();

// populate the list with objects..

return list.Find(o => o.Id == myCriteria);
Todd
+1  A: 

Evidently the performance hit of anonymous delegates is pretty significant.

Test code:

    static void Main(string[] args)
    {
        for (int kk = 0; kk < 10; kk++)
        {
            List<int> tmp = new List<int>();
            for (int i = 0; i < 100; i++)
                tmp.Add(i);
            int sum = 0;
            long start = DateTime.Now.Ticks;
            for (int i = 0; i < 1000000; i++)
                sum += tmp.Find(delegate(int x) { return x == 3; });
            Console.WriteLine("Anonymous delegates: " + (DateTime.Now.Ticks - start));


            start = DateTime.Now.Ticks;
            sum = 0;
            for (int i = 0; i < 1000000; i++)
            {
                int match = 0;
                for (int j = 0; j < tmp.Count; j++)
                {
                    if (tmp[j] == 3)
                    {
                        match = tmp[j];
                        break;
                    }
                }
                sum += match;
            }
            Console.WriteLine("Classic C++ Style: " + (DateTime.Now.Ticks - start));
            Console.WriteLine();
        }
    }

Results:

Anonymous delegates: 710000
Classic C++ Style: 340000

Anonymous delegates: 630000
Classic C++ Style: 320000

Anonymous delegates: 630000
Classic C++ Style: 330000

Anonymous delegates: 630000
Classic C++ Style: 320000

Anonymous delegates: 610000
Classic C++ Style: 340000

Anonymous delegates: 630000
Classic C++ Style: 330000

Anonymous delegates: 650000
Classic C++ Style: 330000

Anonymous delegates: 620000
Classic C++ Style: 330000

Anonymous delegates: 620000
Classic C++ Style: 340000

Anonymous delegates: 620000
Classic C++ Style: 400000

In every case, using anonymous delegates is about 100% slower than the other way.

Nick
No, the performance hit here isn't using the delegate. Your algorithms function fundamentally different, the first method has asymptotic runtime O(n^2) while the second has runtime O(n). This hasn't got anything to do with delegates but rather with using the `Find` function in this context.
Konrad Rudolph