標籤:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace First_exam{ class Student { /// <summary> ///學生姓名的欄位和屬性 /// </summary> private string _Name; public string Name { get { return this._Name; } } private string _Xingbie; /// <summary> /// 學生性別的欄位和屬性 /// </summary> public string Xingbie { get { return this._Xingbie; } } /// <summary> /// 學生年齡的欄位和屬性 /// </summary> private uint _Age; public uint Age { get { return this._Age; } } /// <summary> /// 學產生績的欄位和屬性 /// </summary> private List<LessonScore> _Scores; public List<LessonScore> Scores { get { return this._Scores; } } /// <summary> /// 建構函式,傳入學生姓名,性別,年齡,成績 /// </summary> public Student(string name, string xb, uint age, List<LessonScore> scrs) { this._Name = name; this._Xingbie = xb; this._Age = age; this._Scores = scrs; } public Student(string name, string xb, uint age) { this._Name = name; this._Xingbie = xb; this._Age = age; this._Scores = null; } public override string ToString() { string str; str = string.Format("{0}--{1}--{2}",this._Name, this._Age,this._Xingbie); return str; } } class LessonScore { /// <summary> /// 課程成績的欄位和屬性 /// </summary> private float _Score; public float Score { get { return this._Score; } } /// <summary> /// 課程名稱的欄位和屬性 /// </summary> private string _Lessson; public string Lesson { get { return this._Lessson; } } /// <summary> /// 建構函式 /// </summary> public LessonScore(string les, float scr) { this._Lessson = les; this._Score = scr; } public override string ToString() { string str; str = string.Format("{0}----{1}分", this._Lessson,this._Score); return str; } } class Program { static void Main(string[] args) { Student[] arr = { new Student("張氏那","男",20), new Student("李四","男",23), new Student("李霞","女",21), new Student("王媽媽","女",29), new Student("郭明","男",22), new Student("歐陽夏","女",24), new Student("王丹","女",20), new Student("張寶","男",25), }; var query = from val in arr select val; foreach (Student item in query) { Console.WriteLine(item); } Console.WriteLine(); var query2 = from val in arr select val.Name; foreach(string item in query2) { Console.Write("{0}, ",item); } Console.WriteLine(); Console.WriteLine(); var query3 = from val in arr select val.Name.Length; foreach (int item in query3) { Console.Write("{0}, ", item); } Console.WriteLine(); Console.WriteLine(); var query4 = from val in arr select new { val.Name, val.Age, NameLen = val.Name.Length}; foreach(var item2 in query4) { Console.WriteLine(item2); } } }}
C# LINQ 中關於from和select的一個小例子