Aug 17

Written by: Soul Solutions
Thursday, 17 August 2006 

BronwenWeeGo.jpgWhen i started using the finder in the new generic lists I couldn't find a good e.g of how to write the find function.  So here's a cut down version of one that i ended up writing.

First I needed a class that could work out if a supplied item was equal to something in my list e.g.


using System;
using System.Collections.Generic;
using System.Text
namespace SoulSolutions.Test
{
    /// 
    /// Provides generic functionality to find an object in collection.
    /// 
    public class FindObject
    {
        private int id;
        
        /// 
        /// Constructor
        /// 
        /// The unique identifier for the object.
        public FindObject(int id)
        {
            this.id = id;
        }
        
        /// 
        /// Predicate to use to find a item in a list based on the 
        /// id
        /// 
        /// The object to compare to
        /// true if found/false otherwise
        public bool FindByIdPredicate(PersonObject objectData)
        {
            return objectData.ItemId == id;
        }
    }
}

Then to use it:

Need to create my FindObject class giving it the value i'm looking for.  Then using the list that i want to search, call the find giving it the findobject class with the function that i want to use to find.


List items;
FindObject objectToFind = new FindObject(2);
PersonObject person = items.Find(new Predicate(objectToFind.FindByIdPredicate));

Tags:

1 comment(s) so far...

Re: List.Find

Hi Bronwen,

Thanks for your code example. Like you I too found it hard to get a good example. Your example really helped me, however my client is developing in VB.Net example and I thought I would post a VB.Net example:

Dim ChildProcess As BackgroundWorker = DirectCast(sender, BackgroundWorker)
Dim BgWorkerComparer As New BackGroundWorkerComparer(ChildProcess)
Dim BgWorkerPredicate As New System.Predicate(Of BackgroundWorker)(AddressOf BgWorkerComparer.FindPredicate)
Dim ListItem As BackgroundWorker = _ChildProcesses.Find(BgWorkerPredicate)

Thanks again :-)

By Michael O'Dea-Jones on   Monday, 21 April 2008

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 
Copyright © 2002-2009 Soul Solutions Pty Ltd. | Login