Altinet
  • Home
  • Blog
  • Contact





A nice linq extension (works with linq to nhibernate)

On 03 Apr, 2011
Uncategorized
By : Bruno Samardzic
With 2 Comments
Views : 6165

I needed a classic “where guid in” type of query to do (though i’m not sure if i should be thinking in that way when using linq:) so i poked around a bit, but couldn’t find anything good. So here it is:

        public static IQueryable<T> WhereIn<T,TMember>(this IQueryable<T> query, Expression<Func<T, TMember>> member, IList<TMember> inList) where T : BaseEntity
        {
            if (inList.Count() == 0) return query.Where(x => false);
            Expression<Func<TMember, bool>> expr = x => Enumerable.Contains(inList,x);
            var method = ((MethodCallExpression)expr.Body).Method;
            var expression = Expression.Call(null, method, ((MethodCallExpression)expr.Body).Arguments[0], member.Body);
            var lambda = Expression.Lambda<Func<T, bool>>(expression, "inLambda", member.Parameters);
            return inList.Count() > 0 ? query.Where(lambda) : query.Where(x => false);
        }

A classic example of usage would be something like this

Repository.Query<Partner>().WhereIn(x => x.Guid, partnerGuidList))

We are basically selecting partners by partnerguid, it’s very useful for paging and such.

An ispiration for this type of solution came from the this blog post for catching future values. Hope this helps!



Previous Post Next Post 

About The Author

Bruno Samardzic


Number of Posts : 45
All Posts by : Bruno Samardzic

Comments ( 2 )

  • Marc Mar 12 , 2013 at 9:35 am / Reply

    Simply:

    Repository.Query ().Where(x => partnerGuidList.Contains(x.Guid)))

    though both have the 2100 parameter limit issue with SQL server.

  • kagjes Mar 12 , 2013 at 9:55 am / Reply

    Hmm, i think for some reason that didn’t work out for me when using NHibernate, but i could be wrong, it’s been awhile:)


Leave a Comment

Click here to cancel reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>





Recent Posts

  • Angular vs React: round 2
  • Why programming is hard
  • Orchard Workflows, undocumented gem
  • The React Redux
  • React.js invoicing CRUD application, part 2: Description

Recent Comments

  • Angshuman on Animation for starred grid rows and columns using xaml
  • Advanced Excel Training in Lucknow on Angular vs React: round 2
  • Reginald Sophomore on My example of Angularjs directive
  • Slobodan on Angular and Breeze – story so far.
  • Bruno Samardzic on Reaction to Ember-forged Durandal Angularly Knocking out my Backbone, or my JS MVC framework research conclusion.

Contact

Altinet d.o.o.

OIB: 97429091194

Čulinečka cesta 146, Zagreb

Tel: +385 (1) 2946 819

Mob: +385 (98) 210 756

IBAN: HR4323400091110406470

Latest tweets