Monday, January 9, 2012

Linq IN operator

Sometimes, you might want to extract the "intersection" of the two object lists but the object types are different. For example, you have a customer list and another one is invoice list. You want to get the customers whose "customer_id" exist in the invoice list. This can be done in the SQL syntax easily by using the IN operator. But, there is none in the Linq. So, I have written my own extension:

public static List<T> In<T, T2>(this List<T> list1,
           List<T2> list2,
           Func<T, T2, bool> predicate)
        {
            List<T> result = new List<T>();

           // exit immediately if list2 is empty or null.
            if ((list2 == null)
                || (list2.Count == 0))
            {
                return result;     // return blank list.
            }

            foreach (var item in list1)
            {
                if (list2.Where(n => predicate(item, n)).Count() > 0)
                {
                    result.Add(item);
                }
            }

            return result;
        }

2 comments:

  1. How Do I use this ?
    And maybe it can be converted into Ienumerable ?

    ReplyDelete
    Replies
    1. For example, you need to get the customer object instances store in cust_list which was specified in the selected_customers.

      List cust_list = (data from database)
      List selected_customers = (user key in on the screen)

      var v = cust_list.In(selected_customers,
      (c, s) => c.customer_code == s);

      foreach (var item in v)
      {
      (run your process here)
      }

      Delete