Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a new list with key

Tags:

c#

.net

list

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

List<object> r = new List<object>();  
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
like image 948
VeecoTech Avatar asked Jun 26 '11 08:06

VeecoTech


4 Answers

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;
like image 160
Ahmed Magdy Avatar answered Nov 14 '22 06:11

Ahmed Magdy


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.

like image 43
Illuminati Avatar answered Nov 14 '22 06:11

Illuminati


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);
like image 2
Kirill Polishchuk Avatar answered Nov 14 '22 05:11

Kirill Polishchuk


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

like image 1
Aliza Avatar answered Nov 14 '22 05:11

Aliza