Use a Lambda Expression for Filter Method in CSharp

Description

The following code shows how to use a Lambda Expression for Filter Method.

Example


using System;/*from w  w  w . j a va2  s  .  com*/
using System.Collections;

public delegate bool IntFilter(int i);

public class MainClass {
    public static int[] FilterArrayOfInts(int[] ints, IntFilter filter) {
        ArrayList aList = new ArrayList();
        foreach (int i in ints) {
            if (filter(i)) {
                aList.Add(i);
            }
        }
        return ((int[])aList.ToArray(typeof(int)));
    }
    public static void Main() {
        int[] nums = { 1, 2, 3, 4, 5};
        int[] oddNums = FilterArrayOfInts(nums, i => ((i & 1) == 1));
        foreach (int i in oddNums)
            Console.WriteLine(i);
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor