logo资料库

C#入门教程新手篇.md

表达式

graph LR
A[表达式] --> B[算术表达式]
A --> C[关系表达式]
A --> D[逻辑表达式]
A --> E[条件表达式]
A --> F[Lambda表达式]
A --> G[LINQ表达式]

以下是每种表达式的单独示例:

算术表达式

算术表达式主要包括数值运算符和数值型数据类型,下面是一些完整的示例代码,用于演示算术表达式的不同场景:

using System;

public class Program
{
    public static void Main()
    {
        int x = 7;
        int y = 3;
        int result = 0;

        // 加法
        result = x + y;
        Console.WriteLine($"{x} + {y} = {result}"); // 输出结果为:7 + 3 = 10

        // 减法
        result = x - y;
        Console.WriteLine($"{x} - {y} = {result}"); // 输出结果为:7 - 3 = 4

        // 乘法
        result = x * y;
        Console.WriteLine($"{x} * {y} = {result}"); // 输出结果为:7 * 3 = 21

        // 除法
        result = x / y;
        Console.WriteLine($"{x} / {y} = {result}"); // 输出结果为:7 / 3 = 2(整数除法)

        // 取模
        result = x % y;
        Console.WriteLine($"{x} % {y} = {result}"); // 输出结果为:7 % 3 = 1

        double a = 7.5;
        double b = 3.2;
        double resultDouble = 0.0;

        // 浮点数相加
        resultDouble = a + b;
        Console.WriteLine($"{a} + {b} = {resultDouble}"); // 输出结果为:7.5 + 3.2 = 10.7

        // 浮点数相减
        resultDouble = a - b;
        Console.WriteLine($"{a} - {b} = {resultDouble}"); // 输出结果为:7.5 - 3.2 = 4.3

        // 浮点数相乘
        resultDouble = a * b;
        Console.WriteLine($"{a} * {b} = {resultDouble}"); // 输出结果为:7.5 * 3.2 = 24.0

        // 浮点数相除
        resultDouble = a / b;
        Console.WriteLine($"{a} / {b} = {resultDouble}"); // 输出结果为:7.5 / 3.2 = 2.34375

        // 混合计算
        int c = 2;
        double resultMixed = a + b / c - y * 1.0 / c;
        Console.WriteLine($"{a} + {b} / {c} - {y} * 1.0 / {c} = {resultMixed}"); 
        // 输出结果为:7.5 + 3.2 / 2 - 3 * 1.0 / 2 = 6.85
    }
}

以上代码演示了整数和浮点数的基本数值运算和计算顺序,并展示了混合计算的例子。

关系表达式

关系表达式用于比较两个值之间的关系,常见的关系运算符包括等于(==)、不等于(!=)、大于(>)、小于(<)、大于等于(>=)和小于等于(<=)。下面是一个完整的示例代码,演示了各种关系表达式的使用:

using System;

public class Program
{
    public static void Main()
    {
        int x = 5;
        int y = 7;
        bool result;

        // 相等判断
        result = (x == y);
        Console.WriteLine($"x == y: {result}"); // 输出结果为:x == y: False

        // 不等判断
        result = (x != y);
        Console.WriteLine($"x != y: {result}"); // 输出结果为:x != y: True

        // 大于判断
        result = (x > y);
        Console.WriteLine($"x > y: {result}"); // 输出结果为:x > y: False

        // 小于判断
        result = (x < y);
        Console.WriteLine($"x < y: {result}"); // 输出结果为:x < y: True

        // 大于等于判断
        result = (x >= y);
        Console.WriteLine($"x >= y: {result}"); // 输出结果为:x >= y: False

        // 小于等于判断
        result = (x <= y);
        Console.WriteLine($"x <= y: {result}"); // 输出结果为:x <= y: True

        double a = 3.5;
        double b = 2.8;

        // 浮点数相等判断 (使用 Math.Abs 进行浮点数误差的容忍)
        result = (Math.Abs(a - b) < 0.0001);
        Console.WriteLine($"a ≈ b: {result}"); // 输出结果为:a ≈ b: False

        string str1 = "Hello";
        string str2 = "World";

        // 字符串相等判断
        result = (str1 == str2);
        Console.WriteLine($"str1 == str2: {result}"); // 输出结果为:str1 == str2: False
    }
}

以上代码演示了不同数据类型(整数、浮点数和字符串)之间的关系表达式。注意,在比较浮点数时,为了避免浮点数误差,通常需要使用一个容忍范围进行判断。

逻辑表达式

逻辑表达式用于判断条件是否为真或为假,常见的逻辑运算符包括逻辑与(&&)、逻辑或(||)和逻辑非(!)。下面是一个完整的示例代码,演示了各种逻辑表达式的使用:

using System;

public class Program
{
    public static void Main()
    {
        bool condition1 = true;
        bool condition2 = false;
        bool result;

        // 逻辑与
        result = (condition1 && condition2);
        Console.WriteLine($"condition1 && condition2: {result}"); // 输出结果为:condition1 && condition2: False

        // 逻辑或
        result = (condition1 || condition2);
        Console.WriteLine($"condition1 || condition2: {result}"); // 输出结果为:condition1 || condition2: True

        // 逻辑非
        result = !condition1;
        Console.WriteLine($"!condition1: {result}"); // 输出结果为:!condition1: False

        int x = 5;
        int y = 7;

        // 复合逻辑表达式
        result = (x > 0 && x < 10);
        Console.WriteLine($"x > 0 && x < 10: {result}"); // 输出结果为:x > 0 && x < 10: True

        result = (x > 0 || y < 0);
        Console.WriteLine($"x > 0 || y < 0: {result}"); // 输出结果为:x > 0 || y < 0: True

        result = !(x > 0 && y > 0);
        Console.WriteLine($"!(x > 0 && y > 0): {result}"); // 输出结果为:!(x > 0 && y > 0): False
    }
}

以上代码演示了逻辑与、逻辑或和逻辑非运算符的用法。可以使用一个或多个条件来构建复杂的逻辑表达式,并根据结果判断条件的真假。

条件表达式

条件表达式用于根据条件的真假来选择不同的执行路径。常见的条件表达式包括 if 语句、if-else 语句、switch 语句等。下面是一个完整的示例代码,演示了各种条件表达式的使用:

using System;

public class Program
{
    public static void Main()
    {
        int x = 5;
        int y = 7;

        // if 语句
        if (x < y)
        {
            Console.WriteLine("x 小于 y");
        }

        // if-else 语句
        if (x > y)
        {
            Console.WriteLine("x 大于 y");
        }
        else
        {
            Console.WriteLine("x 不大于 y");
        }

        // if-else if-else 语句
        if (x > y)
        {
            Console.WriteLine("x 大于 y");
        }
        else if (x < y)
        {
            Console.WriteLine("x 小于 y");
        }
        else
        {
            Console.WriteLine("x 等于 y");
        }

        // switch语句
        switch (x)
        {
            case 1:
                Console.WriteLine("x 等于 1");
                break;
            case 2:
                Console.WriteLine("x 等于 2");
                break;
            case 3:
                Console.WriteLine("x 等于 3");
                break;
            default:
                Console.WriteLine("x 不等于 1、2 或 3");
                break;
        }

        // ?: 条件运算符
        string result = (x < y) ? "x 小于 y" : "x 不小于 y";
        Console.WriteLine(result);
    }
}

以上代码演示了常见的条件表达式的用法。

  • if 语句根据条件的真假来决定是否执行特定的代码块。
  • if-else 语句根据条件的真假来选择执行不同的代码块。
  • if-else if-else 语句根据多个条件的真假来选择执行不同的代码块。
  • switch 语句根据一个表达式的值匹配不同的 case 条件,并执行对应的代码块。
  • ?: 条件运算符是一种简洁的写法,根据条件的真假来选择返回不同的值。

Lambda 表达式

将Lambda时,咱们先讲下如下示例:

using System;

public class Program
{
    public static void Main()
    {
        // 作为委托使用
        Calculate add = Add;
        int sum = add(3, 5);
        Console.WriteLine("3 + 5 = " + sum); // 输出结果为:3 + 5 = 8

        Calculate multiply = Multiply;
        int product = multiply(4, 6);
        Console.WriteLine("4 * 6 = " + product); // 输出结果为:4 * 6 = 24

        // 作为参数传递给方法
        ProcessOperation(2, 3, Add); // 输出结果为:2 Add 3 = 5
        ProcessOperation(4, 5, Multiply); // 输出结果为:4 Multiply 5 = 20
    }

    public delegate int Calculate(int x, int y);

    public static int Add(int x, int y)
    {
        return x + y;
    }

    public static int Multiply(int x, int y)
    {
        return x * y;
    }

    public static void ProcessOperation(int x, int y, Calculate operation)
    {
        int result = operation(x, y);
        Console.WriteLine($"{x} {operation.Method.Name} {y} = {result}");
    }
}

Lambda 表达式是 C# 中一种简洁的匿名函数形式,它可以用于创建委托实例或者作为参数传递给方法。Lambda 表达式的语法形式为 input parameters => expression,其中 input parameters 是输入参数列表,expression 是表达式主体。下面是一个相对全面的完整示例代码,演示了 Lambda 表达式的不同应用场景:

using System;

public class Program
{
    public delegate int Calculate(int x, int y);

    public static void Main()
    {
        // 作为委托使用
        Calculate add = (x, y) => x + y;
        int sum = add(3, 5);
        Console.WriteLine("3 + 5 = " + sum); // 输出结果为:3 + 5 = 8

        Calculate multiply = (x, y) => x * y;
        int product = multiply(4, 6);
        Console.WriteLine("4 * 6 = " + product); // 输出结果为:4 * 6 = 24

        // 作为参数传递给方法
        ProcessOperation(2, 3, (a, b) => a + b); // 输出结果为:2 + 3 = 5
        ProcessOperation(4, 5, (a, b) => a * b); // 输出结果为:4 * 5 = 20
    }

    public static void ProcessOperation(int x, int y, Calculate operation)
    {
        int result = operation(x, y);
        Console.WriteLine($"{x} {operation.Method.Name} {y} = {result}");
    }
}

以上代码演示了 Lambda 表达式的两种常见用法:

  1. 将 Lambda 表达式赋值给委托类型的实例,从而创建匿名函数。在示例中,我们定义了一个 Calculate 委托,它接受两个整数参数并返回一个整数。然后使用 Lambda 表达式创建了两个 add 和 multiply 的委托实例,并调用它们来执行加法和乘法运算。

  2. 将 Lambda 表达式作为参数传递给方法。在示例中,我们定义了一个 ProcessOperation 方法,它接受两个整数参数和一个 Calculate 委托类型的参数 operation。在方法内部,我们通过调用传入的委托来执行特定的操作,并输出结果。

Lambda 表达式的灵活性使得它在许多场景下都可以简化代码,并提高可读性和可维护性。

LINQ 表达式

LINQ(Language Integrated Query)是一种在C#中进行数据查询和操作的技术。它提供了一组统一的语法和方法,可以对各种数据源进行查询、筛选、排序和转换操作。下面是一个相对全面的完整示例代码,演示了 LINQ 表达式的不同应用场景:

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

public class Program
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Age = 25 },
            new Person { Name = "Bob", Age = 30 },
            new Person { Name = "Charlie", Age = 35 },
            new Person { Name = "David", Age = 40 }
        };

        // 查询名字以"A"开头的人
        var query1 = from person in people
                     where person.Name.StartsWith("A")
                     select person;
        foreach (var person in query1)
        {
            Console.WriteLine(person.Name);
        }
        // 输出结果为:Alice

        // 查询年龄大于30的人的姓名和年龄
        var query2 = from person in people
                     where person.Age > 30
                     select new { person.Name, person.Age };
        foreach (var person in query2)
        {
            Console.WriteLine($"{person.Name} - {person.Age}");
        }
        // 输出结果为:
        // Charlie - 35
        // David - 40

        // 按年龄升序排序
        var query3 = from person in people
                     orderby person.Age ascending
                     select person;
        foreach (var person in query3)
        {
            Console.WriteLine($"{person.Name} - {person.Age}");
        }
        // 输出结果为:
        // Alice - 25
        // Bob - 30
        // Charlie - 35
        // David - 40

        // 使用方法语法进行查询和操作
        var query4 = people.Where(person => person.Age < 35)
                           .OrderBy(person => person.Name)
                           .Select(person => person.Name);
        foreach (var name in query4)
        {
            Console.WriteLine(name);
        }
        // 输出结果为:
        // Alice
        // Bob
    }
}

以上代码演示了 LINQ 表达式的几种常见用法:

  1. 使用查询表达式(query expression)查询数据。在示例中,我们创建了一个 people 的列表,然后使用查询表达式对其进行查询过滤,筛选出名字以 "A" 开头的人。

  2. 使用查询表达式选择特定的字段。在示例中,我们使用查询表达式选取年龄大于 30 的人的姓名和年龄,并通过匿名类型(anonymous type)来存储结果。

  3. 使用查询表达式进行排序。在示例中,我们使用查询表达式按照年龄升序对人员进行排序。

  4. 使用方法语法(method syntax)进行查询和操作。在示例中,我们使用方法链的方式,通过 WhereOrderBySelect 等方法对数据进行查询和转换。

LINQ 提供了强大且灵活的功能,可以适用于各种数据源(如集合、数据库等)。通过 LINQ,我们可以以一种类似于 SQL 的语法对数据进行查询和操作,简化了我们的代码,并提高了开发效率。

小结

C#的表达式就讲到这里,面对亲情、友情、爱情以及事业和生活,你的“表达式”是什么样的呢,其实这个“表达式”很大程度上决定了我们与世界的和谐度。

大家有任何问题都可以加关注后在评论区留言,或者加客服一对一咨询。

分享到:
收藏