开发者

How to change the name of a item that I am adding to a list of items

I have a class called Contac开发者_C百科t, and a list called contacts, which is a list of the Class Contact.

I have a variable named localContact, which is a Contact.

I want to add localContact, to my list contacts, but I do not want it to be named localContact in the list. I want it to be named localContact.Name (which is a string).

Any ideas?


use a dictionary instead of a list then:

var myDict = new Dictionary<string, Contact>();
myDict[localContact.Name] = localContact;


(Assuming you are talking about a ListBox control)

In the Contact class, override the ToString method.

something like:

public override string ToString()
{
    return this.Name;
}


I think you actually want to use a dictionary collection, so you can retrieve your Contact objects using Contact.Name as the key.

e.g.

// Create the collection
Dictionary<string, Contact> myCollection = new Dictionary<string, Contact>();

// Create your local object
var localContact = new Contact { Name = "MyLocalContact" };

// Add the local object to the collection
myCollection.Add(localContact.Name, localContact);

// Retrieve the local object by name
var myContact = myCollection["MyLocalContact"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜