本人c#初学者,想要把多个对象存入到哈希表中,哈希表的key是对象的一个变量,哈希表的value是对象,请问应该怎么写?
4条回答 默认 最新
码老头 2022-03-29 09:42关注请注意:以下是.NET 6(C# 10的语法)。
示例代码:using System; using System.Collections; using System.Collections.Generic; using System.Linq; var students = new List<Student> { new(1, "Rector", 18), new(2, "James", 20), new(3, "Curry", 22) }; var ht = new Hashtable(students.ToDictionary(x => x.Id, x => x)); foreach (DictionaryEntry entry in ht) { Console.WriteLine($"{entry.Key}==>>{entry.Value}"); } public record Student(int Id, string Name, int Age);运行结果:
3==>>Student { Id = 3, Name = Curry, Age = 22 } 2==>>Student { Id = 2, Name = James, Age = 20 } 1==>>Student { Id = 1, Name = Rector, Age = 18 }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报 编辑记录解决 1无用