C#中One Key值字典的多个值? [英] multiple values for One Key values dictionary in C#?
问题描述
假设地址对象有...
城市: Kanpur
状态:UP
而在第二个地址对象中有
城市:Rajsthan
州:MP
现在我如何将它添加到通用集合中。
我已经尝试过下面的代码。但没有得到什么是正确的方法。
foreach(entity.Addresses中的var objAddress)
{
ds =新字典< string,string> ;();
ds.Add(City,(objAddress.City == null)?:objAddress.City);
ds.Add(State,(objAddress.State == null)?:objAddress.State.ToString());
lsb.Add(ds.ToString());
}
只需使用 Dictionary< string,List< Address>>
。
添加到该词典时,如果给定的键还没有包含一个值,添加包含该地址的新的列表< Address>
。
如果给定的键包含一个值,简单地添加
新的地址
到列表
。
I have an Address object in this object I have address lines. My problem is that I want to add different values for same keys. This object can have multiple addresses so I need to add property of address as key and value as value in a dictionary.
suppose object of address one have...
City : Kanpur
State:UP
and in second object of address have
City : Rajsthan
State:MP
now how can I add it in a generic collections.
I have tried below code. but not getting what is right approach.
foreach (var objAddress in entity.Addresses)
{
ds = new Dictionary<string, string>();
ds.Add("City", (objAddress.City == null) ? "" : objAddress.City);
ds.Add("State", (objAddress.State == null) ? "" : objAddress.State.ToString());
lsb.Add(ds.ToString());
}
Just use a Dictionary<string, List<Address>>
.
When adding to that Dictionary, if a given key doesn't yet contain a value, add a new List<Address>
that contains that address.
If the given key does contain a value, simply Add
the new Address
to that List
.
这篇关于C#中One Key值字典的多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!