当索引不可用时,如何访问IDictionary对象中的KeyValuePair? [英] How to access the KeyValuePair in a IDictionary object when index is not available ?

查看:51
本文介绍了当索引不可用时,如何访问IDictionary对象中的KeyValuePair?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我在尝试访问元素时有一个要求,即存储在IDictionary对象中的KeyValuePair对象,但问题是它们的顺序是可更新的.我想将KeyValuePair对象中的每个值"存储在不同的类对象中 为此我创建的.可以说我正在做一些映射工作.但是唯一的问题是所有元素的输入顺序都可以更新.他们的钥匙"也可以更新.

I have a requirement where I am trying to access the elements i.e. KeyValuePair objects stored in a IDictionary object but the problem is their order is updatable. I want to store each of the 'Value' from the KeyValuePair object in a different class object which I created for this purpose. We can say that I am doing some mapping kind of stuff. But the only problem is the input order of all the elements can be updated. Also their 'Key' can be updated.

如何提取此类信息?

请帮助,在此先谢谢

这里有一个示例与我正在尝试做的事情有关.

Here is a sample relates what I am trying to do.

Dictionary<object, object> Author = new Dictionary<object, object>();
 
Author.Add("Name", "John Smith"); //Later it "Name" can be "FullName" just for an example
Author.Add("Age", 25);
Author.Add("DOB", "1996-08-06");
            
// I am trying to extract this info in my Author class as

AuthorClass author1 = new AuthorClass();
author1.Name = (string)Author.ElementAt(0).Value;
author1.Age = Convert.ToInt32(Author.ElementAt(1).Value);             
author1.DOB = Convert.ToDateTime(Author.ElementAt(2).Value);



// The AuthorClass Class
class AuthorClass
{
     public string Name { get; set; }
     public int Age { get; set; }
     public DateTime DOB { get; set; }
}


 此处,当作者"元素的顺序更改时,代码将失败.请帮助解决此问题.


 Here when the order of 'Author' elements changes, the code will fail. Please help to resolve this. 

推荐答案

嗨!

使用键名代替"ElementAt(index)".

Use the name of the key instead of "ElementAt(index)".

例如:

AuthorClass author1 = new AuthorClass();
author1.Name = (string)Author["Name"];
author1.Age = Convert.ToInt32(Author["Age"]);             

如果它对您有好处,您可以将此答案标记为您的问题的答案吗?


这篇关于当索引不可用时,如何访问IDictionary对象中的KeyValuePair?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆