2010년 8월 23일 월요일

How to find objects in a Generic List's Find method


How to find objects in a Generic List's Find method



Here is a simple class:

public class Customer
{
  public int ID;
  public string Name;
}


A list of Customers that can be found using either customer ID or customer name, that is, I need to implement the two Finds of the Customers below:

public class Customers : List<Customer>
{
  public Customer Find(int customerID) { ... }
  public Customer Find(string customerName) {...}
}

Solution 1: Loop through each item.

public class Customers : List<Customer>
{
  public Customer Find(int customerID)
  {
    foreach (Customer customer in this)
    {
      if (customer.ID == customerID)
          return customer;
    }
    return null;
  }

  public Customer Find(string customerName)
  {
    foreach (Customer customer in this)
    {
      if (customer.Name == customerName)
        return customer;
    }
    return null;
}


Solution 2: Use the Generic List's Find method with predicate:

class Customers : List<Customer>
{
  private class Matcher
  {
    int m_id;
    string m_name;

    public Matcher(int id) { m_id = id; }
    public Matcher(string name) { m_name = name; }

    public bool MatchID(Customer customer)
    {
      return (m_id == customer.ID);
    }
    public bool MatchName(Customer customer)
    {
      return (m_name = customer.Name);
    }
  }

  public Customer Find(int id)
  {
    Matcher matcher = new Matcher(id);
    return this.Find(matcher.MatchID);
  }

  public Customer Find(string name)
  {
    Matcher matcher = new Matcher(name);
    return this.Find(matcher.MatchName);
  }
}


Solution 3: Use List's Find with anonymous delegates. It put the delegate in the scope of the of the method I am implementing.


public class Customers : List<Customer>
{
  public Customer Find(int id)
  {
    return Find(delegate(Customer c) { return id == c.ID; });
  }

  public Customer Find(string name)
  {
    return Find(delegate(Customer c) { return name == c.Name; });
  }


Solution 4: Use Lambda Expressions (.NET 3.x) 

public class Customers : List<Customer>  
{  
  public Customer Find(int id)  
  {  
    return this.Find(customer => customer.ID == id);  
  }  
 
  public Customer Find(string name)  
  {  
    return this.Find(customer => customer.Name == name);  
  }  
}

댓글 없음:

댓글 쓰기