C# List相關應用


以一個team類別的TeamPlayerData List為範例

public class team
{
    public int playerNumber;
    public string playerName;
    public float playerHeight;
    public float playerWeight;
}

List<team> TeamPlayerData = new List<team>();

List搜尋條件(Exists、FindIndex)

搜尋是否有這個球員姓名
如果有則回傳true,沒有則false

bool isExists2 = TeamPlayerData.Exists(n => n.playerName == "Curry");

搜尋球員姓名的index
如果有回傳符合條件的第一個index,沒有則index為-1

int index = TeamPlayerData.FindIndex(n => n.playerName == "Curry");

List新增多筆、複製轉移(AddRange)

List<team> TeamPlayerData = new List<team>();
List<team> newTeamData = new List<team>();
TeamPlayerData.AddRange(newTeamData);
//newTeamData複製到TeamPlayerData List

清空List(Clear)

TeamPlayerData.Clear();

新增items、印出List(Add、foreach)
這邊使用到foreach來印出List,如果是同樣的資料型態List可以不用指定object

team newteam = new team();
newteam.playerNumber = 30;
newteam.playerName = "Curry";
TeamPlayerData.Add(newteam);

team newteam2 = new team();
newteam2.playerNumber = 23;
newteam2.playerName = "Lebron";
TeamPlayerData.Add(newteam2);

foreach (team item in TeamPlayerData)
{
    Console.WriteLine(item.playerNumber + " " + item.playerName);
}

/*印出
30 Curry
23 Lebron
*/

Remove、RemoveAt用法
可以看到兩行的目的都是移除同一個item
只不過Remove是指定要移除誰,而RemoveAt則是用index去選擇

List<string> LeagueTeamData = new List<string>();
LeagueTeamData.Add("Warriors");
LeagueTeamData.Add("Lakers");
LeagueTeamData.Add("Heat");

//擇一
LeagueTeamData.Remove("Lakers");
LeagueTeamData.RemoveAt(1);

雙層List

List<List<string>> LeagueTeamData = new List<List<string>>();
LeagueTeamData.Add(new List<string>() { "Warriors", "Golden State"});
LeagueTeamData.Add(new List<string>() { "Lakers", "Los Angeles"});
#C# #Winform







你可能感興趣的文章

Modern Web 2018 簡短心得

Modern Web 2018 簡短心得

mac m1晶片踩坑記

mac m1晶片踩坑記

Vue.js 學習旅程Mile 1 – 歡迎介紹篇

Vue.js 學習旅程Mile 1 – 歡迎介紹篇






留言討論