C#中One Key值字典的多个值? [英] multiple values for One Key values dictionary in C#?

查看:129
本文介绍了C#中One Key值字典的多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Address对象在这个对象我有地址线。我的问题是我想为相同的键添加不同的值。这个对象可以有多个地址,所以我需要添加地址的属性作为键和值作为字典中的值。



假设地址对象有...

 城市: 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屋!

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