纵码过河山 2020-04-26 14:42 采纳率: 66.7%
浏览 959
已采纳

c#的字典如何根据key,不每项列举能获取value内的所有元素?

例如有下面的数据:

ID,  a,    b,    c,   d
1,   甲,   0,    +,   x
2,   乙,   00,   -,   y
3,   丙,   000,  /,   z

我先以ID为key,其他为Value的元素生成字典:

public class Information
{
    public int ID;
    public string a;
    public string b;
    public string c;
    public string d;
}

创建字典:

private Dictionary<int, Information> InforDict = new Dictionary<int, Information>(); 

字典添加value的元素:

Information infor = new Information(); 
//Infor.a=xxx……
InforDict.Add(infor.ID, infor); 

根据ID获取Value:

InforDict.TryGetValue(ID, out infor); 

现在要获取value(infor)内的所有元素:a, b, c, d时,有没有什么办法避免采用列举 infor.a, infor.b,infor.c,infor.d这样,而用循环就能获取当前Key的所有元素值和元素名?

比如key=1的时候,就能输出“a 甲, b 0, c +, d x?”

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-04-26 14:48
    关注
    public class Information
    {
        public int ID {get;set;}
        public string a{get;set;}
        public string b{get;set;}
        public string c{get;set;}
        public string d{get;set;}
    }
    
    if (InforDict.TryGetValue(ID, out infor))
    {
    foreach (var prop in infor.GetType().GetPropertites())
    {
    Console.WriteLine("{0}, {1}", prop.Name, prop.GetValue(infor, null));
    }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入