开发者

Linq - Is there are way to build up a linq statement from several snippets of linq

I have several methods that use similar linq statements but different enough for them to be in their own methods. So say, for the sake of arguemnt, I had the following linq snippet which is repeated across all methods (the real snippets would be much longer than this):

        where su.ObjId == serviceUserId
        where cl.StaffMemberId == staffMemberId

If I was working in SQL开发者_如何学JAVA I could just contatenate the repeated SQL as follows:

private string GetRepeatedSql()
{
 return "where su.ObjId = serviceUserId and cl.StaffMemberId = staffMemberId";
}

private void DoSomething()
{
 string mySql = "Select * from ...... lots of sql .." + GetRepeatedSql() + ".. some more sql";
}

(Usual health warnings around contatenating SQL string together noted).

Is there something equivalent in Linq? I'm sick of having to make changes in several places - this seems to contravene the DRY principle.

Thanks!


Correct me if I'm wrong but I always thought LINQ statements weren't executed until you actually used them. (Coming from LINQ to NHibernate)

If that is actually the case you could simply just add whatever you need to the existing statement. For example:

var temp=from x in Sometable select x;

Then adding a where clause:

temp = from x in temp where x.ID==1234 select x;

Then order by

temp=from x in temp order by x.ID select x;

I won't lie I have never done it this way but I assume it should work. If someone knows this won't work please explain why. Thanks.

Found this on msdn: http://msdn.microsoft.com/en-us/library/bb397906.aspx

In LINQ the execution of the query is distinct from the query itself; in other words you have not retrieved any data just by creating a query variable.

So by creating the variable you have not retrieved any data. Although maybe the way I'm doing it above would return data because I am calling from x in temp to change the query.


I do it like this

IQueryable<Publication> pubs = GetPubs();
pubs = ApplySort(pubs, SortBy);
pubs = GetPage(pubs, PageSize, Page);

private IQueryable<Publication> GetPage(IQueryable<Publication> pubs, int PageSize, int Page)
{
   return pubs.Skip(PageSize * (Page - 1)).Take(PageSize);
}

private IQueryable<Publication> ApplySort(IQueryable<Publication> pubs, string SortBy)
{
 switch (SortBy)
  {
   case "Latest": return pubs.OrderByDescending(p => p.Posted);
                  break;
   default: return pubs.OrderByDescending(p => p.Posted);
            break;
  }
}


You can use PredicateBuilder to do this:

The Albahari one here is one I've used recently although there are others around: http://www.albahari.com/nutshell/predicatebuilder.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜