本人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无用
悬赏问题
- ¥20 西门子S7-Graph,S7-300,梯形图
- ¥50 用易语言http 访问不了网页
- ¥50 safari浏览器fetch提交数据后数据丢失问题
- ¥15 matlab不知道怎么改,求解答!!
- ¥15 永磁直线电机的电流环pi调不出来
- ¥15 用stata实现聚类的代码
- ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
- ¥20 docker里部署springboot项目,访问不到扬声器
- ¥15 netty整合springboot之后自动重连失效
- ¥15 悬赏!微信开发者工具报错,求帮改