2009-07-22 讓Linq 支持Where In 3880 0 LinQ 摘要:讓Linq 支持Where In 文章出處:http://george.tsiokos.com/posts/2007/11/30/linq-where-x-in/public static IQueryable<TSource> WhereIn<TSource, TKey> ( this IQueryable<TSource> source1, Expression<Func<TSource, TKey>> keySelector, IEnumerable<TKey> source2) { if (null == source1) throw new ArgumentNullException ("source1"); if (null == keySelector) throw new ArgumentNullException ("keySelector"); if (null == source2) throw new ArgumentNullException ("source2"); Expression where = null; foreach (TKey value in source2) { Expression equal = Expression.Equal ( keySelector.Body, Expression.Constant (value, typeof (TKey)) ); if (null == where) where = equal; else where = Expression.OrElse (where, equal); } return source1.Where<TSource> ( Expression.Lambda<Func<TSource, bool>> ( where, keySelector.Parameters)); }用法:var q = (from u in db.Users where u.LastLogin > new DateTime (2007, 5, 1) orderby u.LastLogin descending select new { u.FirstName, u.LastName, u.UserName, u.LastLogin } ).WhereIn (u => u.UserName, new string[] { "A", "B", "C" }); 回首頁