--- tags: C# --- # C#筆記 ## 限制字數的方法: ``` csharp = string content = string.LimitDisplay(20,”...”); //限制前台顯示字數並加... ``` ## Take, Skip - Take 抓取幾個值 ex: ``` csharp= foreach(var item in list.Take(3)){...} // 抓取3筆資料 ``` - Skip 略過幾個值,通常和Take一起搭配使用 ex: ``` csharp= foreach(var item in list.Skip(3)){...} //略過前3個值後繼續尋訪下去 ``` 應用: 換頁 ## LINQ 常用 - Where 過濾 用來抓取想要的資料,像mysql的Where條件使用。 - Select 提取選取資料其中某幾筆欄位 完整範例: ``` csharp= using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQPractice2Orderby { class Pet { public string Name { get; set; } //get 存取子 "提供",將該值(字串)進行判斷、處理再回傳 //set 存取子 "設定",用於處理計算及邏輯處理 public int Age { get; set; } } class Program { static void Main(string[] args) { Pet[] pets = { new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 }, new Pet { Name="BoBo", Age=3}, new Pet{Name="Coco",Age=3 }}; Dictionary<int,Pet> pdic = new Dictionary<int, Pet>() { {101,new Pet{Name="Coco",Age=3 } } }; IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age); foreach (Pet pet in query) { Console.WriteLine("{0} - {1}", pet.Name, pet.Age); } Console.WriteLine("---------------------------------"); IEnumerable<Pet> desQuery = pets.OrderByDescending(pet => pet.Age); foreach (Pet pet in desQuery) { Console.WriteLine("{0} - {1}", pet.Name, pet.Age); } Console.WriteLine("----------Where, StartsWith-------------"); foreach(Pet pet in pets.Where(x => x.Name.StartsWith("B"))) //.Select(o =>new Pet { Name = o.Name}) 提取資料 { Console.WriteLine("{0} - {1}",pet.Name,pet.Age); } Console.WriteLine("----------Select, GroupBy-------------"); var ages = pets.Select(o => new Pet { Age = o.Age }).GroupBy(o=>o.Age); foreach(var age in ages) { Console.WriteLine("Age {0}: {1}",age.Key,age.Count()); } Console.WriteLine("----------Join, GroupJoin-------------"); } } } ``` ## 取得網址的方法 [網頁](https://blog.miniasp.com/post/2008/02/10/How-Do-I-Get-Paths-and-URL-fragments-from-the-HttpRequest-object) ## HtmlHelper提供方法 ### 一般類 | 方法 | 功能 | | -------- | -------- | | Action、RenderAction | 載入另一個Action | | Partial、RenderPartial (常用) | 載入另一個Partial View | | ActionLink | 提供actionName、controllerName、routeValues產生一個\<a>標籤 | | RouteLink | 提供routeName、routeValues產生一個\<a>標籤 | | AntiForgeryToken | 自動產生一個防止偽造攻擊的Token | | Encode | 傳回一個經過編碼後的HTML字串 | | Raw (常用) | 將傳入字串完整輸出,避免進行HTML編碼 | ### 表單類 Student是Controller的名稱;Create是Controller裡面的method(也就是Action) ``` csharp= @using (Html.BeginForm("Create", “Student", FormMethod.Post, new { enctype = "multipart/form-data" , id="CityId" })) { } //與上面相同 <form action="/Student/Create" enctype="multipart/form-data" id="CityId" method="post"> </form> ``` 表單中常用的input Html.TextBox