多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 可索引集合 ``` List<int> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; List salmons = ["chinook", "coho", "pink", "sockeye"]; salmons.Remove("coho"); salmons.Add("coho"); ``` 由[List](https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1)使用的`Galaxy`类在代码中定义 ``` private static void IterateThroughList() { var theGalaxies = new List<Galaxy> { new (){ Name="Tadpole", MegaLightYears=400}, new (){ Name="Pinwheel", MegaLightYears=25}, new (){ Name="Milky Way", MegaLightYears=0}, new (){ Name="Andromeda", MegaLightYears=3} }; foreach (Galaxy theGalaxy in theGalaxies) { Console.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears); } // Output: // Tadpole 400 // Pinwheel 25 // Milky Way 0 // Andromeda 3 } public class Galaxy { public string Name { get; set; } public int MegaLightYears { get; set; } } ``` ## 键/值对集合 [Dictionary](https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.generic.dictionary-2)类 字典集合 创建`Dictionary`集合并通过使用`foreach`语句循环访问字典 ``` private static void IterateThruDictionary() { Dictionary<string, Element> elements = BuildDictionary(); foreach (KeyValuePair<string, Element> kvp in elements) { Element theElement = kvp.Value; Console.WriteLine("key: " + kvp.Key); Console.WriteLine("values: " + theElement.Symbol + " " + theElement.Name + " " + theElement.AtomicNumber); } } public class Element { public required string Symbol { get; init; } public required string Name { get; init; } public required int AtomicNumber { get; init; } } private static Dictionary<string, Element> BuildDictionary() => new () { {"K", new (){ Symbol="K", Name="Potassium", AtomicNumber=19}}, {"Ca", new (){ Symbol="Ca", Name="Calcium", AtomicNumber=20}}, {"Sc", new (){ Symbol="Sc", Name="Scandium", AtomicNumber=21}}, {"Ti", new (){ Symbol="Ti", Name="Titanium", AtomicNumber=22}} }; ```