Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...