How does the predicate works?

Shervan360 1,641 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);
   }
}

.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,028 questions
C#
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.
11,168 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 68,956 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.

    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 Answers by the question author, which helps users to know the answer solved the author's problem.