开发者

Generate a new list with key

i would like to create a new list with key and values

List<object> r = new List<object>开发者_StackOverflow;();  
r.Add("apple");  
r.Add("John");  
return r;

when u Addwatch the r, you will see

[1] = apple  
[2] = John

Questions: How do i make the [1] and [2] to be new key? When i addwatch the r, i would like to see [1] is replaced by Name. something as below:

Name = apple  
TeacherName = John


Do you mean you want to use something like Dictionary<TKey, TValue>

example:

Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Name", "Apple");
d.Add("Teacher", "John");

or do you want an object to more strongly typed? in this case you have to use your one class / struct

class MyObject
{
 public string Name {get; set;}
 public string Teacher {get; set;}
}

Then

var list = new List<MyObject>();
list.Add(new MyObject { Name = "Apple", Teacher = "John" });
list.Add(new MyObject { Name = "Banana", Teacher = "Setphan" });

then you can all it

var item = list[0];
var name = item.Name;
var teacher = item.Teacher;


It is completely incorrect to use a list for this kind of a data structure. You need to use use Dictionary , NameValueCollection or similar type.


You can transform your list:

List<object> r = new List<object>();
r.Add("apple");
r.Add("John");
r.Add("orange");
r.Add("Bob");

var dict = r.Where((o, i) => i % 2 == 0)
    .Zip(r.Where((o, i) => i % 2 != 0), (a, b) => new { Name = a.ToString(), TeacherName = b.ToString() });

foreach (var item in dict)
{
    Console.WriteLine(item);
}

Output:

{ Name = apple, TeacherName = John }
{ Name = orange, TeacherName = Bob }

And then transform to dictionary:

var result = dict.ToDictionary(d => d.Name, d => d.TeacherName);


You will need to use a Dictionary to do this. Not a List. See http://msdn.microsoft.com/en-us/library/xfhwa508.aspx


I hope i dont make any syntax mistakes here...

Dictionary <string, int> r = new Dictionary<string,int>();
r.add("apple",1);
r.add("John",2)
console.WriteLine(r["apple"]);//returns value 1


Your question is not clear and hard to understand.

Do you mean to say you want keys instead of indexes ? Like Name instead of 1

Well then as Aliza and Bumble Bee have said you need to use a Dictionary instead of a List.

Here's a small example

IDictionary<string, Interval> store = new Dictionary<string, string>();

store.Add("Name","apple");
store.Add("TeacherName ", John);

foreach(KeyValuePair<string, string> e in store)
     Console.WriteLine("{0} => {1}", e.Key, e.Value);   
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜