1. 程式人生 > 實用技巧 >舉個栗子講C#的linq查詢的使用場景

舉個栗子講C#的linq查詢的使用場景

 1 namespace ConsoleApplication1
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             //場景一:找到strs集合中包含“A”的字串,然後已大寫字串和字串長度的形式轉存出來。
 8             //{Word="AS",Length=2},{Word="SPA",Length=3}
 9             //最原始的方式
10             var strs = new string[] { "
is", "as", "spa" }; 11 List<Word> words = new List<Word>(); 12 foreach (var str in strs) 13 { 14 var upper = str.ToUpper(); 15 if (upper.Contains("A")) 16 { 17 words.Add(new Word() { Str = upper, Length = upper.Length });
18 } 19 } 20 //現在的讀取方式 21 var query = from str in strs 22 let upper = str.ToUpper() //定義臨時變數 23 where upper.Contains("A") 24 select new { Str=upper, Length=upper.Length }; 25 }
26 } 27 class Word 28 { 29 public string Str { get; set; } 30 public int Length { get; set; } 31 } 32 }