Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

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

Wednesday, February 23, 2011

Dynamic sorting using Linq Expression

You may wonder how to avoid hard coding the sorting order in the list. Here is one of the solution using Linq Expression:

class MyClass
{
   public int age { get; set; }
   public string name { get; set; }
}

MyClass[] arr =
{
   new MyClass() {age = 10, name ="abc" },
   new MyClass() {age = 20, name ="xyz" },
   new MyClass() {age = 30, name ="cde" }
};


// create the parameter
ParameterExpression param = Expression.Parameter(typeof(MyClass), "i");

// create the property to be used base on the 
// type (ie, MyClass) in the param variable. 
// you may change the "name" to any other field.
Expression prop = Expression.Property(param, "name");

// construct the lambda expression.
Expression> lambda 
   = Expression.Lambda>(prop, param);

// compile it to a function.
Func compile = lambda.Compile();

// now, we can use the function by passing it 
// to the OrderBy() proc.
var v3 = arr.OrderBy(compile);

string s;
foreach (var item in v3)
{
   s = item.name;
}

Tuesday, October 19, 2010

Linq literals

Check this out if you are passing the string into Where():

http://msdn.microsoft.com/en-us/library/bb399176.aspx