Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Lambda Expression Return if Predicate returns true

Tags:

c#

I am confused if the parameter fruit (which I know is an input parameter) is returned if the condition is true for predicate. As the following piece of code signifies:

List<string> fruits = new List<string> {
    "apple",
    "passionfruit",
    "banana",
    "mango",
    "orange",
    "blueberry",
    "grape",
    "strawberry"
};

IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 8);
// query contains: {apple,banana,mango,orange,grape}

IEnumerable<string> query2 = query.Where(fruit => fruits.Contains("apple"));

foreach (string fruity in query2)
{
    Console.WriteLine(fruity);
}

// finally returns: {apple,banana,mango,orange,grape}

Therefore it seems as if input is returned if condition is true.

Kindly guide me if I'm wrong

like image 449
Sadiq Avatar asked Sep 04 '26 21:09

Sadiq


2 Answers

Where returns a filtered sequence of the input for which the predicate returned true. It is applied to each element in turn, and that item is either yielded or discarded. Basically:

public static IEnumerable<T>(this IEnumerable<T> source, Func<T,bool> predicate)
{
    foreach(var el in source) {
        if(predicate(el) {
            yield return el;
        }
    }
}

Look at the names:

IEnumerable<string> query2 = query.Where(fruit => fruits.Contains("apple"));

That says, for every fruit, see if the entire set (fruits, note the final s) returns an apple. The list fruits does contain apple, so that is true for every fruit.

You possibly meant:

IEnumerable<string> query2 = query.Where(fruit => fruit.Contains("apple"));
like image 96
Marc Gravell Avatar answered Sep 07 '26 10:09

Marc Gravell


LINQ Where returns an IEnumerably set with all items that the predicate returns true for.

In your second query you're doing fruits.Contains("apple"), which is basically always true, or always false. Perhaps you meant to do the following:

IEnumerable<string> query2 = query.Where(fruit => fruit == "apple");
//returns: {apple}
like image 33
Destrictor Avatar answered Sep 07 '26 11:09

Destrictor