[C#] Func及Action的快速Demo

2023-03-18,,

参考代码1:

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

namespace FuncActionDemo
{
    class FuncActionTest
    {
        public void Test1(List<int> data, Func<int, bool> filter)
        {
            var result = data.Where(x => filter(x)).ToList();
            result.ForEach(x =>
            {
                Console.WriteLine(x);
            }
            );

        }
        public void Test2(List<int> data, Action<int, int> action)
        {
            var d = data.OrderBy(x => x).ToList();
            action(d[0], d[1]);

        }
        public void Test3(List<int> data, Func<int, int,int> func)
        {
            var d = data.Where(x => x%2==1).ToList();
            int iOddAccSum=  d.Aggregate(func);
            Console.WriteLine("Odd Acc Sum:"+iOddAccSum.ToString());

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            FuncActionTest faTest = new FuncActionTest();
            List<int> data = new List<int> { 1, 2, 4, 7, 8, 9 };
            faTest.Test1(data, x => {
                if (x % 2 == 0)
                    return true;
                else
                    return false;
            });
            faTest.Test1(data, x => { return FilterEven(x); });
            faTest.Test1(data, FilterEven);
            Console.WriteLine("-----------");
            faTest.Test2(data, Add);
            faTest.Test3(data,Acc);
        }
        static bool FilterEven(int s)
        {
            if (s % 2 == 0)
                return true;
            else
                return false;
        }
        static void Add(int a, int b)
        {
            Console.WriteLine(a + b);
        }

        static int Acc(int a, int b)
        {
            return a * 10 + b;
        }
    }
}

参考代码2:

using System;
using System.Linq; namespace AggregateDemo
{
class Program
{
static void Main(string[] args)
{
string[] words = new string[] { "My", "Name", "Is", "Zhang San" };
string s = words.Aggregate((a, n) => a + " " + n);
Console.WriteLine(s); int[] ints = new int[] { 1,2,3,4,5,6};
int iSum = ints.Aggregate(1000,(a, b) => a*10+b);
Console.WriteLine(iSum);
}
}
}

参考代码3:

[C#] Func及Action的快速Demo的相关教程结束。

《[C#] Func及Action的快速Demo.doc》

下载本文的Word格式文档,以方便收藏与打印。