开发者

Using Where() with a dynamic Func fails, but works with a hard coded Where() clause

开发者 https://www.devze.com 2023-03-24 05:06 出处:网络
See the two Linq (to SharePoint) code samples below. 开发者_StackOverflow中文版 The only differences are the highlighted sections of code.The first statement works as expected with a hard-coded where

See the two Linq (to SharePoint) code samples below.

开发者_StackOverflow中文版

The only differences are the highlighted sections of code. The first statement works as expected with a hard-coded where clause, but the 2nd set of code throws the error “Value does not fall in within the expected range” when I try to do a count on the items. What am I missing?

Works

relatedListItems = dc.GetList<GeneralPage>("Pages")
    .Where(x => x.RelatedPracticesTitle.Any(y=>y=="Foo"))                           

if (relatedListItems.Count() == 0)
                    {…}

Fails - “Value does not fall within the expected range”

Func<GeneralPage, bool> f = x => x.RelatedPracticesTitle.Any(y => y == "Foo");
relatedListItems = dc.GetList<GeneralPage>("Pages")                         
    .Where(f)                                  

if (relatedListItems.Count() == 0)
                    {…}


If it's LINQ to Sharepoint, presumably that means it should be using expression trees, not delegates. Try:

Expression<Func<GeneralPage, bool>> f = 
    x => x.RelatedPracticesTitle.Any(y => y == "Foo");
relatedListItems = dc.GetList<GeneralPage>("Pages").Where(f);

By the way, it's generally a better idea to use Any() rather than Count() if you just want to find out if there are any results - that way it can return as soon as it's found the first one. (It also expresses what you're interested in more clearly, IMO.)


In the first case, you're using the Expression<Func<GeneralPage, bool>> overload and pass an expression which I assume LINQ to SharePoint will try to convert to CAML and execute.

In the second case, you're passing the plain Func<GeneralPage, bool> so LINQ to SharePoint can't figure out how to compose a query (it only sees the delegate, not the expression).

0

精彩评论

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