---
# System prepended metadata

title: 考試筆記
tags: [考試筆記]

---

# 考試筆記
###### tags: `考試筆記`
using System.IO;

using System.Text.Json;

using System.Windows.Forms.DataVisualization.Charting;

using GMap.NET;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers; 
using GMap.NET.MapProviders; 

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

Gmap元件:
```csharp=
寫在button
放在json的foreach跟if 裡面執行
//gMap元件設置
gMapControl1.MapProvider = GMapProviders.GoogleMap; //設定地圖來源網站 GMapProviders+s
gMapControl1.DragButton = MouseButtons.Left; //設定成左鍵(預設右鍵) //Drag(拖動)          
gMapControl1.MinZoom = 5; //最小比例
gMapControl1.MaxZoom = 20; //最大比例
gMapControl1.Zoom = 15; //當前比例 (放在min max後面)
gMapControl1.ShowCenter = false; //不顯示中心十字
//設定定位點
double lat = Convert.ToDouble(obj.lat); //緯度y
double lng = Convert.ToDouble(obj.lng); //經度x
PointLatLng point = new PointLatLng(lat, lng); //宣告定位點物件，並導入緯經度
gMapControl1.Position = point; //gmap元件的中心點位置

//Overlay:
//宣告圖層物件
GMapOverlay overlay = new GMapOverlay();
                    
//Markers:                
GMapMarker marker = new GMarkerGoogle(point, GMarkerGoogleType.red_dot); //位置給googlemap
marker.ToolTipText = obj.sna; //在標記目標位置點加入提示字

//在蓋之前，把原本的先刪掉
overlay.Markers.Clear();
gMapControl1.Overlays.Clear();

overlay.Markers.Add(marker); //Makers蓋在Overlay
gMapControl1.Overlays.Add(overlay); //Overlay蓋在Map control
```

.
tabcontrol元件:
```csharp=
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
    .....讀檔...宣告陣列...
    tabcontrol1 > 閃電 > 動作 > select:tabControl1_Selected
        
    if (e.TabPage == tabPage1)
    {
        chart1.Series["Series1"].Points.DataBindXY(datelist, openlist);
    }
    if (e.TabPage == tabPage2)
    {
        chart2.Series["Series1"].Points.DataBindXY(datelist, closelist);
    }
    if (e.TabPage == tabPage3)
    {
        chart3.Series["Series1"].Points.DataBindXY(datelist, volumelist);
    }
}
```

.
Chart元件:
```csharp=
//Chart using:
using System.Windows.Forms.DataVisualization.Charting;

//Title名稱:
//要先手動從屬性增加Titles成員
chart1.Titles["Title1"].Text = "柱狀圖";

//資料 導入/清除:
chart1.Series["Series1"].Points.DataBindXY(xvalues, yvalues);
chart1.Series["Series1"].Points.Clear();

//Label 顯示/隱藏:
chart1.Series["Series1"].IsValueShownAsLabel = true; (預設Y值)
chart1.Series["Series1"].Label = "#VALY";
chart1.Series["Series1"].Label = "";

//Marker座標點 顯示/隱藏:
chart1.Series["Series1"].MarkerStyle = MarkerStyle.Triangle;
chart1.Series["Series1"].MarkerSize = 8;
chart1.Series["Series1"].MarkerSize = 0;

//Series1的資料顯示在圖例(Legend)(右上)的字:
chart1.Series["Series1"].LegendText = "我是Series1";

//隱藏chart1:
chart1.Visible = false;
//開啟3D:
chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
//關閉圖例:
chart1.Legends["Legend1"].Enabled = false;
//設定成折線圖:
chart1.Series["Series1"].ChartType = SeriesChartType.Line;
//圓餅圖 and 顯示百分比:
chart1.Series[0].ChartType = SeriesChartType.Pie;
chart1.Series["Series1"].Label = "#VALX\n#PERCENT{P1}";
chart1.Series["Series1"].LegendText = "#VALX: [#PERCENT{P1}]";
//雜:
chart1.Legends["Legend1"].DockedToChartArea = "ChartArea1"; //圖例顯示在圖表內
chart1.Series["Series1"].LabelFormat = "#,###"; //金錢格式
chart1.Series["Series1"].LegendText = titleArr[0];
```

.
ImageList元件
```csharp=
//imageList1 > 屬性 > Images > 加入圖片(next、prev、001)
button2.ImageList = imageList1;
button2.ImageIndex = 0;

//自己宣告ImageList元件
ImageList imageList2 = new ImageList(); //宣告imageList元件
mageList2.ColorDepth = ColorDepth.Depth32Bit;
imageList2.ImageSize = new Size(248, 248);
foreach (string name in namelist)
{
    imageList2.Images.Add(Image.FromFile(path + name));
}

//debug資料夾
var path = Environment.CurrentDirectory + "/pictures/";
```

.
picturebox+timer元件
```csharp=
//pictureBox1控制項 > 屬性 > 行為 > SizeMode:StretchImage (依照picturebox尺寸塞入)
//timer1控制項 > 屬性 > 行為 > Interval:1000
//timer1控制項 > 屬性 > 閃電 > tick:timer1_tick
string path = @"C:\Users\小餅\source\repos\c_sharp\PictureBox_Timer\pictures\";
string[] images = { "001.jpg", "002.jpg", "003.jpg", "004.jpg", "005.jpg" };
string[] names = { "超人特攻隊2", "功夫熊貓3", "艾莉塔：戰鬥天使", "水行俠","馴龍高手3" };
int current = 0;
private void Form1_Load(object sender, EventArgs e)
{
    pictureBox1.Image = Image.FromFile(path + images[0]); //用Image的method => FromFile
    label1.Text = names[0];
}

private void button1_Click(object sender, EventArgs e)
{
    timer1.Enabled = true;
}

private void button2_Click(object sender, EventArgs e)
{
    timer1.Enabled = false;
}

private void timer1_tick(object sender, EventArgs e)
{
    if (current == images.Length) //current == 6 時
    {
        current = 0;
    }
    pictureBox1.Image = Image.FromFile(path + images[current]);
    label1.Text = names[current];
    current++;
}
```

.
OpenFileDialog元件:
```csharp=
private void button1_Click(object sender, EventArgs e)
{
   openFileDialog1.Title = "Select a file";  
   openFileDialog1.InitialDirectory = "C:";  
   openFileDialog1.FileName = "";            
   openFileDialog1.Filter = "All files (*.*)|*.*";
    
   //openFileDialog1.Filter = "text files (*.txt)|*.txt|All files (*.*)|*.*";
            
   if (openFileDialog1.ShowDialog() == DialogResult.OK) 
   {
       textBox1.Text = openFileDialog1.FileName;
   }
    textBox2.Text = File.ReadAllText(textBox1.Text);
}
```

.
Opendata JSON:
```csharp=
var jsontext = File.ReadAllText(@"C:\Users\小餅\source\repos\opendata_lab\youbike\toyuan-ubike.json");
var jsonparse = JsonDocument.Parse(jsontext); 
var jsonrootelement = jsonparse.RootElement;  

foreach (var element in jsonrootelement.GetProperty("retVal").EnumerateArray()) 
{    
        var obj = element.Deserialize<objclass>();                                   
        //矩陣的一項裡又分兩個物件(貼上兩個objectclass)
        var objweather1 = element.GetProperty("A").Deserialize<objclassA>();
        var objweather2 = element.GetProperty("B").Deserialize<objclassB>(); 

    
///////////////////////////////////////////////////////////////////////////////////////////    
Console.WriteLine(jsonrootelemant.GetProperty("RD").GetDateTime().ToString("yyyy-MM-dd"));
////////////////////////////////////////////////////////////////////////////////////////////////
//"NO":{"NA": [ 1, 2, 3 ]}
Console.WriteLine(string.Join(", ",jsonrootelemant.GetProperty("NO").GetProperty("NA").EnumerateArray().Select(   o => o.GetInt32().ToString()  ).ToArray()));
//                      (以, 分開陣列元素並印出)                                                                (列舉1 , 2 , 3 取成整數再轉字串)   把字串1,2,3轉成陣列
////////////////////////////////////////////////////////////////////////////////////    
var props = jsonrootelemant.GetProperty("NO").EnumerateObject(); //把NO裡的所有屬性(Key+value)轉成列舉物件
while (props.MoveNext()) //往前列舉，if有東西列舉也回傳true
{
    var obj = props.Current; //宣告物件obj存取當前列舉的物件
    Console.WriteLine($"Prop[{obj.Name}]/{obj.Value.ValueKind}/{obj.Value.GetRawText()}");
}
    
    
}
```

.
DataGridView元件:
```csharp=
DataTable table = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.DataSource = table;
    table.Columns.Add("價錢");    
}
private void button1_Click(object sender, EventArgs e)
{
    table.Rows.Clear();
    table.Rows.Add(obj.sno, obj.sna, obj.ar);
}
```

.
List
```csharp=
加入元素:
List<int> intlist = new List<int>();
intlist.Add(5);

陣列轉串列(宣告):
int[] intarray = { 2, 3, 5, 6 };
List<int> intlist = new List<int>(intarray);
```

.
List 演算法:
```csharp=
//方法1:
List<string> filter_areaname_list = areaname_list.Distinct().ToList();

//方法2:
List<string> filter_areaname_list = new List<string>();
for (int i = 0; i < areaname_list.Count; i++)
{
    if (filter_areaname_list.IndexOf(areaname_list[i].ToLower()) == -1)  
    {
        filter_areaname_list.Add(areaname_list[i]);
    }
}
```

.
ListBox:
```csharp=
listBox1.SelectedItem.ToString()
    
listBox1.SelectedItems.Count
    
```

.
雜物:
```csharp=
$"平均: {Mean:F5}"
    
字串陣列轉整數陣列:
string[] a = { "1", "2", "3" };
int[] b = Array.ConvertAll(a, int.Parse);

離開：
Application.Exit();

MessageBox:
MessageBox.Show(result)

時間:
DateTime.Now.Year
```

.
計算:
```csharp=
int[] data_array = {5,3,2,7,2,8,2,8};

            //Find maximum:
int max;
max = data_array[0]; //拿第0項跟後面比較
for (int i = 0; i < data_array.Length; i++)
{
    if (data_array[i] > max)
    {
                    max = data_array[i];
    }
}
            
//Find minimum:
int min;
min = data_array[0];
for (int i = 0; i < data_array.Length; i++)
{
    if (data_array[i] < min)
    {
                    min = data_array[i];
    }
}
            
//Find average:
double sum = 0;
double average;
foreach (double data in data_array)
{
    sum += data;
}
average = sum / data_array.Length;
            
//Find SD: 平方和除以項數 減掉 平均數的平方 再開根號
double powersum = 0;
double SD;
foreach (double data in data_array)
{
    powersum += Math.Pow(data,2);
}
SD = Math.Sqrt((powersum / data_array.Length) - Math.Pow(average, 2));
```

.
StreamReader存成二維陣列(不寫死)
```csharp=
string path = @"C:\Users\小餅\OneDrive\code_resource\AAPL.csv";

//計算 row_num，column_num:
//一定要設ln，不然在if內會多叫到一次sr.ReadLine
int row_num = 0, column_num = 0;
string ln;
StreamReader sr1 = new StreamReader(path);
while ((ln = sr1.ReadLine())!= null)
{
    if (column_num == 0)
        {
            column_num = ln.Split(',').Length;
        }
        row_num++;
}

//存入二維陣列
int arrayindex = 0;
string[,] data = new string[row_num,column_num];
StreamReader sr2 = new StreamReader(path);
while ((ln = sr2.ReadLine())!= null)
{
    string[] array = ln.Split(',');
    for(int i = 0 ; i < column_num ; i++)
    {
        data[arrayindex,i] = array[i];
    }
    arrayindex++;
}
```

