Tuesday, January 17, 2012

Convert Bitmap to Icon

This is quite easy to achieve by using the following procedure:

        public static Icon ToIcon(Bitmap bmp)
        {
            IntPtr i = bmp.GetHicon();
            Icon ic = Icon.FromHandle(i);

            return ic;
        }

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