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
164 views
in Technique[技术] by (71.8m points)

LINQ with non-lambda for Any Contains

How do you do Linq with non-lambda express for the following (which does not work):

string[] words = { "believe", "relief", "receipt", "field" }; 
var wd = (from word in words
          select word).Any(Contains ("believe"));
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's not clear what good you believe the from wor in words select wor is doing - it's really not helping you at all.

It's also not clear why you don't want to use a lambda expression. The obvious approach is:

bool hasBelieve = words.Any(x => x.Contains("believe"));

Note that this isn't checking whether the list of words has the word "believe" in - it's checking whether the list of words has any word containing "believe". So "believer" would be fine. If you just want to check whether the list contains believe you can just use:

bool hasBelieve = words.Contains("believe");

EDIT: If you really want to do it without a lambda expression, you'll need to basically fake the work that the lambda expression (or anonymous method) does for you:

public class ContainsPredicate
{
    private readonly string target;

    public ContainsPredicate(string target)
    {
        this.target = target;
    }

    public bool Apply(string input)
    {
        return input.Contains(target);
    }
}

Then you can use:

Func<string, bool> predicate = new ContainsPredicate("believe");
bool hasBelieve = words.Any(predicate);

Obviously you really don't want to do that though...

EDIT: Of course you could use:

var allBelieve = from word in words
                 where word.Contains("believe")
                 select word;

bool hasBelieve = allBelieve.Any();

But that's pretty ugly too - I'd definitely use the lambda expression.


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

...