【C#】编写LINQ查询 & 多线程linq

using System;
using System.Linq;
using static System.Console;

namespace LinqWithObjects
{
    class Program
    {
        static void LinqWithArrayOfStrings()
        {
            var names = new string[] { "Michael", "Pam", "Jim", "Dwight",
        "Angela", "Kevin", "Toby", "Creed" };

            // var query = names.Where(
            //   new Func<string, bool>(NameLongerThanFour));

            // var query = names.Where(NameLongerThanFour);

            var query = names
              .Where(name => name.Length > 4)
              .OrderBy(name => name.Length);

            foreach (string item in query)
            {
                WriteLine(item);
            }
        }

        static void LinqWithArrayOfExceptions()
        {
            var errors = new Exception[]
            {
                new ArgumentException(),
                new SystemException(),
                new IndexOutOfRangeException(),
                new InvalidOperationException(),
                new NullReferenceException(),
                new InvalidCastException(),
                new OverflowException(),
                new DivideByZeroException(),
                new ApplicationException()
            };

            var numberErrors = errors.OfType<ArithmeticException>();//异常数组中属于算术异常的项
            //System.OverflowException: Arithmetic operation resulted in an overflow.
            //System.DivideByZeroException: Attempted to divide by zero.
            foreach (var error in numberErrors)
            {
                WriteLine(error);
            }
        }

        static bool NameLongerThanFour(string name)
        {
            return name.Length > 4;
        }

        static void Main(string[] args)
        {
            // LinqWithArrayOfStrings();
            LinqWithArrayOfExceptions();
            ReadLine();
        }
    }
}

多线程linq

using System;
using static System.Console;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;

namespace LinqInParallel
{
    class Program
    {
        static void Main(string[] args)
        {
            var watch = new Stopwatch();
            Write("Press ENTER to start: ");
            ReadLine();
            watch.Start();

            IEnumerable<int> numbers = Enumerable.Range(1, 2_000_000_000);

            // var squares = numbers
            //   .Select(number => number * number).ToArray();

            var squares = numbers.AsParallel()
              .Select(number => number * number).ToArray();

            watch.Stop();
            WriteLine("{0:#,##0} elapsed milliseconds.",
              arg0: watch.ElapsedMilliseconds);
            ReadLine();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/cxyhjl/article/details/130241595