行易软件

少谈技术,多谈应用

博客园 首页 新随笔 联系 订阅 管理
参考代码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:

 

posted on 2022-12-02 18:50  行易软件技术团队  阅读(14)  评论(0编辑  收藏  举报