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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With