Share via

How does the predicate works?

Shervan360 1,681 Reputation points
2025-01-03T16:20:04.48+00:00

Hello,

I am reading the following code from Microsoft Docs. The predicate has two parameters, a string and an index. We don't use an index or any int parameter in the Linq query.

How does the Linq query get the index(int) parameter? From where?

Thanks

Screenshot 2025-01-03 194536

using System;
using System.Collections.Generic;
using System.Linq;

public class Func3Example
{
   public static void Main()
   {
      Func<String, int, bool> predicate = (str, index) => str.Length == index;

      String[] words = { "orange", "apple", "Article", "elephant", "star", "and" };
      IEnumerable<String> aWords = words.Where(predicate).Select(str => str);

      foreach (String word in aWords)
         Console.WriteLine(word);
   }
}

Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

  1. Bruce (SqlWork.com) 83,981 Reputation points
    2025-01-03T17:11:31.37+00:00

    The Where function has a delegate that’s passed two parameters. The first is the item (must match the datatype) in the collection, the second is the index of the item in the collection.

    The Where function loops thru the collection passing the item and the index to the delegate. If the delegate returns true, current item added to a new collection that the Where function returns. note: the Where function is a static extension function, so its hidden argument is the collection.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.