[英]how can I add a value to the list from the Dictionary<int,Object> and the list is in the Object
Ok.. I've seen some similar discussions so I hope this is unique enough. 好的,我看过类似的讨论,所以我希望这足够独特。
I would like to initialize and modify data in a List 我想初始化和修改列表中的数据
The list is a Property of the class User, which is inside a Dictionary 该列表是User类的Property,它位于Dictionary内
http://ideone.com/0YtpnC http://ideone.com/0YtpnC
internal class User
{
public string ID { get; set; }
public string Name { get; set; }
public List<ContactNumber> AddressBook { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
Dictionary<int, User> dic = new Dictionary<int, User>();
dic.Add(1, new User { ID = "id1", Name = "name1" });
dic.Add(2, new User { ID = "id2", Name = "name2" });
dic.Add(3, new User { ID = "id3", Name = "name3", AddressBook = new List<ContactNumber>(){new ContactNumber(3432),new ContactNumber(3213)} });
User user = dic.Where(z => z.Value.ID == "id3").FirstOrDefault().Value;
Console.WriteLine(user.Name);
DisplayList(user);
//Console.WriteLine(user.AddressBook.ToString());
//update the list
addOrUpdate(dic,3,user);
//var used = new User { ID = "id1", Name = "Harry" };
//dic[1] = used;
user = dic.Where(z => z.Value.ID == "id3").FirstOrDefault().Value;
Console.WriteLine(user.Name);
DisplayList(user);
}
private static void DisplayList(User user)
{
foreach (ContactNumber number in user.AddressBook)
{
Console.WriteLine(number.PhoneNumber);
}
}
//determin list length
public static void addOrUpdate(Dictionary<int, User> dic, int key, User user)
{
//sets a new user data and just replaces it in the dictionary
//var used = new User { ID = "id1", Name = "Harry" };
var used = new User{ ID = "id3", Name = "Henry" ,AddressBook = new List<ContactNumber>(){new ContactNumber(3111),new ContactNumber(4444)}};
if (dic.TryGetValue(key, out user))
{
// yay, value exists!
dic[key] = used;
}
else
{
// darn, lets add the value
dic.Add(key, used);
}
}
}
the problem is I want to get the user info and just add a contact number to the list. 问题是我想获取用户信息,只需将联系人号码添加到列表中。 Currently it rewrites the entire list since I make a new version of list in the update function. 当前,由于我在更新功能中创建了新版本的列表,因此它将重写整个列表。
http://ideone.com/iI2Rxb只需: dic[key].AddressBook.Add(new ContactNumber(666));
Wont below help, just add to the list (since it is referenced, it will update whatever you have been getting from the dictionary) 不需要帮助,只需将其添加到列表中(由于已被引用,它将更新您从词典中获得的内容)
user.AddressBook.Add(...new contact number); user.AddressBook.Add(...新的联系电话);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.