好的..我看过一些类似的讨论,所以我希望这是非常独特的。
我想初始化和修改List中的数据
该列表是User类的属性,它位于Dictionary
中 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);
}
}
}
问题是我想获取用户信息,只需在列表中添加联系人号码即可。目前,它重写了整个列表,因为我在更新函数中创建了新版本的列表。
答案 0 :(得分:0)
http://ideone.com/iI2Rxb
只是:
dic[key].AddressBook.Add(new ContactNumber(666));
答案 1 :(得分:0)
答案 2 :(得分:0)
不在帮助之下,只需添加到列表中(因为它被引用,它将更新你从字典中获得的任何内容)
user.AddressBook.Add(...新联系人号码);