Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

c# - Reuse of a LINQ query

This is not about the reuse of a result but more the statement itself. Nor is it about an error when using var as mentioned in: LINQ to SQL: Reuse lambda expression

Out of sheer curiosity I was wondering if it is possible to reuse a single LINQ statement.

Lets say I have the following LINQ statement:

.Where(x => x.Contains(""));

Is it possible to extract the statement x => x.Contains("") and use some kind of reference to this for later usage in, lets say, another class?

So I can call it like: .Where(previouslySavedStatement);

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can store it in a variable. If you are working with IQueryable then use:

System.Linq.Expressions.Expression<Func<Foo, bool>> selector = x => x.Contains("");

If you are using IEnumerable then use:

Func<Foo, bool> selector = x => x.Contains("");

And use it in your query:

query.Where(selector);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...