using System;
using System.Collections.Generic;
using System.Linq;
class MainClass
{
static List<Student> stu = new List<Student>()
{
new Student(){ Id=1,Name="小明",Age=18,Score=100},
new Student(){ Id=2,Name="小梅",Age=19,Score=80},
new Student(){ Id=3,Name="小刘",Age=21,Score=50},
new Student(){ Id=4,Name="小美",Age=20,Score=60}
};
static void Main(string[] args)
{
//目的:1.将stu的数据转移到tea 2.Title=学生姓名+“老师”
List<Teacher> tea = new List<Teacher>();
foreach (var student in stu)
{
Teacher teacher = new Teacher();
teacher.Id = student.Id;
teacher.Name = student.Name;
teacher.Age = student.Age;
teacher.Score = student.Score;
teacher.Title = student.Name + "老师";
tea.Add(teacher);
}
}
}
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Score { get; set; }
}
class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Score { get; set; }
public string Title { get; set; }
}
二、遍历(含增加实体)
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass
{
static List<Student> stu = new List<Student>()
{
new Student(){ Id=1,Name="小明",Age=18,Score=100},
new Student(){ Id=2,Name="小梅",Age=19,Score=80}
};
static void Main(string[] args)
{
foreach (var student in stu)
{
if (student.Id == 1)
{
student.value = new List<Value>(){
new Value(){ value=100 },
new Value(){ value=1000 }
};
}
else if (student.Id == 2)
{
student.value = new List<Value>(){
new Value(){ value=200 },
new Value(){ value=2000 }
};
}
}
// 输出所有学生的信息
foreach (var student in stu)
{
Console.WriteLine($"Id:{student.Id}, Name:{student.Name}, Score:{student.Score},Listvalue:{string.Join(',', student?.value.Select(x=>x.value))}");
}
}
}
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Score { get; set; }
public List<Value> value { get; set; }
}
class Value
{
public int id { get; set; }
public int value { get; set; }
}
三、参数任何值类型T的用法
public class ReturnResultDto<T>//初始化需要传入指定类型T
{
public int RetCode { get; set; }
public string Message { get; set; }
public T ReturnData { get; set; }//T代表类型可以是任意的,若需列表可改成List<T>
}
public class Student
{
public int id { get; set; }
public string Name { get; set; }
}
public class Test
{
static int Main(string[] args)
{
var test = new ReturnResultDto<Student>();
test.RetCode = 500;
test.Message = "success";
test.ReturnData = new Student { id = 1, Name = "张三" };
return 0;
}
}