-1

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"));
Cœur
  • 37,241
  • 25
  • 195
  • 267
Nate Pet
  • 44,246
  • 124
  • 269
  • 414
  • This question which is very similar appears to have been asked here: http://stackoverflow.com/questions/1566439/linq-help-with-contains-and-a-lambda-query – Dessus Dec 14 '11 at 21:35

2 Answers2

3

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank Jon, how can you do it with non-lamda as I like to see how it is done. – Nate Pet Dec 14 '11 at 21:30
  • 1
    @NatePet: See my edit, but it's not really clear whether that's what you mean. What exactly did you have in mind by "non-lambda"? – Jon Skeet Dec 14 '11 at 21:33
0

You could do it like that

string[] words = { "believe", "relief", "receipt", "field" };
var wd = (from wor in words
          where wor.Contains("believe")
          select wor);
JuChom
  • 5,717
  • 5
  • 45
  • 78