C# Predicate

0

Category :

Predicate is a functional construct providing a convenient way of basically testing if something is true of a given T object.

The Predicate will always return a boolean, by definition.
Predicate is basically identical to Func
List of People objects and we need to find if one is named Oscar:

Old Method

Person oscar = null;
foreach (Person person in people) {
    if (person.Name == "Oscar") {
        oscar = person;
        break;
    }
}

if (oscar != null) {
    // Oscar exists!
}
If we need to find someone with a different name then we will need a lot more code using this method.

Predicate

Using Predicates involves much less code and maybe easier to read....maybe
Predicate oscarFinder = (Person p) => { return p.Name == "Oscar"; };
Predicate ruthFinder = (Person p) => { return p.Name == "Ruth"; };
Predicate seventnYOFinder = (Person p) => { return p.Age == 17; };

Person oscar = people.Find(oscarFinder);
Person ruth = people.Find(ruthFinder);
Person seventeenYearOld = people.Find(seventnYOFinder );


my thanks to:
http://stackoverflow.com/questions/1710301/what-is-a-predicate-in-c

C# Yield

0

Category :

The following example shows the two forms of the yield statement.

1. Yield Break

You can use a yield break statement to end the iteration.

2. Yield Return expression

Return each iterator element one at a time. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

C# Example:

    static void Main()
    {
        // Display powers of 2 up to the exponent of 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }

    public static IEnumerable Power(int number, int exponent)
    {
        int result = 1;

        for (int i = 0; i < exponent; i++)
        {
            result = result * number;
            yield return result;
        }
    }

    // Output: 2 4 8 16 32 64 128 256

Control flow:

1. Hits foreach
2. Enters Power method
3. Yield return result
4. Returns to outer foreach
5. Console write
6. Next loop of foreach re-enters Power method
7. Remembers previous value of "result"
8. And so oooooon......

Main Uses

Custom Iteration: No need for temp collection to store result-set that matches criteria.
Stateful Iteration: Keeping track of state during foreach

my thanks to:

https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
https://www.youtube.com/watch?v=4fju3xcm21M