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
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"));
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With