HTLF

一步一个脚印,走出高度...

导航

C#中常用方法说明

Join

字符串连接 string.Join

// 一个简单的字符串数组
string[] fruits = { "Apple", "Banana", "Orange" };

// 使用逗号作为分隔符,将数组中的所有元素连接成一个字符串
string result = string.Join(",", fruits);

// 输出结果: "Apple,Banana,Orange"
Console.WriteLine(result);

LINQ 连接 Enumerable.Join

  • 用于将两个数据序列(例如两个对象列表)基于一个共同的键(Key)进行关联,类似于 SQL 数据库中的 INNER JOIN
  • 语法: 序列1.Join(序列2, 序列1的键选择器, 序列2的键选择器, 结果选择器)
// 定义两个简单的类
public class Student { public int Id { get; set; } public string Name { get; set; } }
public class Score { public int StudentId { get; set; } public int Points { get; set; } }

// 创建两个数据源
var students = new List<Student> { new Student { Id = 1, Name = "Alice" }, new Student { Id = 2, Name = "Bob" } };
var scores = new List<Score> { new Score { StudentId = 1, Points = 95 }, new Score { StudentId = 1, Points = 88 } };

// 使用 LINQ Join 将学生和他们的分数关联起来
var query = students.Join(
    scores,                              // 要连接的第二个序列
    student => student.Id,               // 从第一个序列中提取键 (Student.Id)
    score => score.StudentId,            // 从第二个序列中提取键 (Score.StudentId)
    (student, score) => new { student.Name, score.Points } // 定义结果的结构
);

// 遍历结果
foreach (var item in query)
{
    // 输出: Alice 95, Alice 88
    Console.WriteLine($"{item.Name} {item.Points}");
}

posted on 2026-04-22 15:56  HTLF  阅读(2)  评论(0)    收藏  举报