---
# System prepended metadata

title: '[112]天方科技 ASP.net core 教育訓練 1120323(Vue介接API、C#String格式、條件運算式、迴圈)'

---

# [112]天方科技 ASP.net core 教育訓練 1120323(Vue介接API、C#String格式、條件運算式、迴圈)
## Vue介接API測試
### index.html放在IIS預設網站資料夾 C:\inetpub\wwwroot
![](https://i.imgur.com/VElIS2k.png)

### 直接在http://localhost/ 開啟
![](https://i.imgur.com/qnZJqBD.png)

### 需確定API url正確
![](https://i.imgur.com/equM0h8.png)

![](https://i.imgur.com/EDv4Bb3.png)

## Linq 簡介
Language Integrated Query (LINQ) 是一組以直接將查詢功能整合至 C# 語言為基礎之技術的名稱。
 您可以使用相同的基本查詢運算式模式，來查詢並轉換 SQL 資料庫、ADO .NET 資料集、XML 文件及資料流，以及 .NET 集合中的資料。

### 查詢運算式(宣告式)

```csharp=
IEnumerable<int> scoreQuery =
    from score in scores
    where score > 80
    select score;
```
### 方法運算式(Lambda )

```csharp=
IEnumerable<int> scoreQuery =
    scores 
    .Where(a => a.score > 80)
    .Select(a => a.score);
    
```

參考：
[**Language Integrated Query (LINQ)**](https://learn.microsoft.com/zh-tw/dotnet/csharp/linq/)

[**LINQ寫法：類SQL查詢語法 vs 方法串接**](https://blog.darkthread.net/blog/linq-sql-query-vs-methods/)

### 下列範例示範完整的查詢作業。 完整的作業包括建立資料來源、定義查詢運算式，並在 foreach 陳述式中執行查詢。

```csharp=
// Specify the data source.
int[] scores = { 97, 92, 81, 60 };

// Define the query expression.
IEnumerable<int> scoreQuery =
    from score in scores
    where score > 80
    select score;

// Execute the query.
foreach (int i in scoreQuery)
{
    Console.Write(i + " ");
}

// Output: 97 92 81
```

## C#語法
### 最上層語法

1.using 命名空間。
2.陳述式、函式。
3.自行定義的命名空間與型別。
當建置專案時不使用最上層陳述式時，會將`namespace、class、static void Main()`刪除，等待Compiler時再產生

不使用最上層陳述式，添加方法時選擇在using下方任何位置都可以執行，如果要新增類別則是要選在`app.Run()`之後
```csharp=
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Text.Json.Serialization;
using WebApplication1.Models;

namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args){} //Entry Point
    }
}
```
![](https://i.imgur.com/gbGCAQp.png)
![](https://i.imgur.com/Vn0BBdu.png)



### 宣告變數
變數名稱不要使用數字開頭，使用英文字母或者"_"
```csharp=
int price; 
//or
int price,tax; //通過","宣告多個變數
```

```csharp=
price = 10;
//or
int price = 10; //宣告變數且賦值，稱為變數初始化
```

```csharp=
//隱含型別，變數型別是未知，由"="後的值決定型別
var price = 20; //int
var price = ""; //string
```

```csharp=
//物件型變數
 confic = new ServiceConfiguration();
```

```csharp=
//調用在物件內的方法/屬性
<instanceName>.<memberName>

//Example
var config = new ServiceConfiguration();
//調用LoadConfiguration方法
config.LoadConfiguration();

//取得ApplicationName屬性的值
var applicationName = config.ApplicationName;

//設定DatabaseServerName屬性的值
config.DatabaseServerName = "78.45.81.23";
```

### 型別轉換

```csharp=
int a = 4;
long b = 5;
b = a; //int(4byte) 、long(8byte)，小的可以放入大的，大的不能放入小的

//明確轉換型別
int a = (int)b
string s;
a = (byte)b;  //同樣為整數可以成功轉換
a = (float)b;  //浮點數與整數直接轉換會失敗
s = (string)b;  //()內無法使用string
↓
s = b.ToString();
```
```csharp=
//Convert.方法
string possibleInt = "123";
int count = Convert,Int32(possibleInt);
```

```csharp=
//TryParse or Parse方法
//文字轉數字
int a;
string s = "1234";
//Parse
a = int.Parse(s); 
//TryParse，變成回傳bool的方法，可搭配if函式使用
if(int.TryParse(s, out a)){
    //要做的事
}

```

## String格式變化
使用"+"來串接字串，串接後的新字串會使用新的記憶體區域，舊字串的使用的記憶體並不會消失，變成系統垃圾，所以當要大量字串串接時，建議使用StringBuilder
```csharp=
StringBuilder sb = new StringBuilder();
sb.Append("23");
sb.Append(", Main Street");
sb.Append(", Buffalo");
string address = sb.ToString();
```

### 跳脫字元
```csharp=
//C#解讀輸出
//regular string ，解讀"\\" → "\"
string oldPath = "C:\\inetpub\\wwwroot";
//verbatim string，使用"@"，只解讀""→"
string oldPath = @"C:\inetpub\wwwroot";
string name = @"I Am ""Eric""";
//Output:I Am "Eric"

//\t→tab鍵
string columns = "Column 1\tColumn 2\tColumn 3";
//Output: Column 1        Column 2        Column 3

//\r\n→換行
string rows = "Row 1\r\nRow 2\r\nRow 3";
/* Output:
    Row 1
    Row 2
    Row 3
*/

//\"→"
string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
//Output: "The Æolean Harp", by Samuel Taylor Coleridge
```
### Raw string
使用 """，不會解讀特殊字元，
C# 版本11之後可使用
```csharp=
string singleLine = """Friends say "hello" as they pass by.""";
string multiLine = """
    "Hello World!" is typically the first program someone writes.
    """;
string embeddedXML = """
       <element attr = "content">
           <body style="normal">
               Here is the main text
           </body>
           <footer>
               Excerpts from "An amazing story"
           </footer>
       </element >
       """;
// The line "<element attr = "content">" starts in the first column.
// All whitespace left of that column is removed from the string.

string rawStringLiteralDelimiter = """"
    Raw string literals are delimited 
    by a string of at least three double quotes,
    like this: """
    """";
```
### String interpolation
內插語法，使用$"{變數}"
C# 版本10之後可使用
```csharp=
var jh = (firstName: "Jupiter", lastName: "Hammon", born: 1711, published: 1761);
Console.WriteLine($"{jh.firstName} {jh.lastName} was an African American poet born in {jh.born}.");
Console.WriteLine($"He was first published in {jh.published} at the age of {jh.published - jh.born}.");
Console.WriteLine($"He'd be over {Math.Round((2018d - jh.born) / 100d) * 100d} years old today.");

// Output:
// Jupiter Hammon was an African American poet born in 1711.
// He was first published in 1761 at the age of 50.
// He'd be over 300 years old today.
```

### 後綴字元
L or l for **long**
D or d for **double**
F or f for **float**
M or m for **decimal**
U or u for **unsigned integer**
UL or ul for **unsigned long**
```csharp=
//Type Suffix
int a = 100d; //出現error，因為int無法賦予double的值
double b = 50/3f; //f = float

```

參考：
[**Strings - C# Programming Guide**](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/)
[**C# Special Characters**](https://www.w3schools.com/cs/cs_strings_chars.php)
[**彙整從 C# 1.0 到 C# 11.0 的字串格式變化**](https://blog.miniasp.com/post/2023/01/10/CSharp-String-Literals-Syntax-Collection)

## 條件運算式
**C#教材 20483B-ENU-TrainerHandbook1─Lesson 3 page1-19**

參考：
[**C#運算式**](https://learn.microsoft.com/zh-tw/dotnet/csharp/language-reference/language-specification/expressions#1112-logical-operators)

if 運算式
```csharp=
if (response == "connection_failed") 
{...
 }else if(response == "connection_error")
{...
 }else
{}
```
switch 運算式
```csharp=
//常用寫法
switch(response)
{
    case "connection_failed":
        ...
        break;
    case "connection_ok" :        //兩個條件都符合
    case"connection_susccess":
        ...
        break;
    default :                    //無條件符合時做什麼
        ...
        break;
}

//新式switch寫法(lambda)

public enum Direction
    {
        Up,
        Down,
        Right,
        Left
    }

    public enum Orientation
    {
        North,
        South,
        East,
        West
    }

    public static Orientation ToOrientation(Direction direction) => direction switch
    {
        Direction.Up    => Orientation.North,
        Direction.Right => Orientation.East,
        Direction.Down  => Orientation.South,
        Direction.Left  => Orientation.West,
        _ => throw new ArgumentOutOfRangeException(nameof(direction), $"Not expected direction value: {direction}"),
    };
```

## 迴圈
**C#教材 20483B-ENU-TrainerHandbook1─Lesson 3 page1-21**

參考：
[**Jump 語句- break 、 continue 、 return 和 goto**](https://learn.microsoft.com/zh-tw/dotnet/csharp/language-reference/statements/jump-statements)

for迴圈
```csharp=
for (int i = 0 ; i < 10; i++)  //i++ → i = i + 1 or i += 1
{ 
 // Code to execute. 
} 
```

foreach迴圈
```csharp=
//使用linq時不知道資料上限為多少，所以都使用foreach
string[] names = new string[10]; 
// Process each name in the array. 
foreach (string name in names)
{ 
 // Code to execute. 
} 
```

while迴圈(break, continue, goto)
```csharp=
//判斷成立才執行
bool dataToEnter = CheckIfUserWantsToEnterData(); 
while (dataToEnter)  
{ 
 // Process the data. 
 dataToEnter = CheckIfUserHasMoreData(); 
}
```

do迴圈(break, continue, goto)
```csharp=
//先執行再做判斷
do
{ 
 // Process the data. 
 moreDataToEnter = CheckIfUserHasMoreData(); 
} while (moreDataToEnter); 
```

