Click here to Skip to main content
15,914,481 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
Hi All,

i have a
C#
List<object> dataList


and i need to convert to
C#
Dictionary<object, string> SearchData = new Dictionary<object, string>();
?
Posted
Updated 18-Mar-19 19:08pm
Comments
DamithSL 26-Dec-14 4:24am    
so what will be the key and value of dictionary?
Indukanth 26-Dec-14 4:36am    
in my datalist it is contain some text value..
its look like http://pbrd.co/1HKoh04

i need to give Id as the key and Subject as the value.
DamithSL 26-Dec-14 4:49am    
how you create dataList? can't you use List<someclass> for your requirement rather than object list?
DamithSL 26-Dec-14 4:58am    
update the question with how you create dataList, then we will able to provide better solution for you
Praveen Kumar Upadhyay 26-Dec-14 5:02am    
Please update your question here.

C#
var res = list.ToDictionary(x => x, x => x);

The first lambda lets you pick the key, the second one picks the value.

You can play with it and make values differ from the keys, like this:

C#
var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));

If your list contains duplicates, add Distinct() like this:

C#
var res = list.Distinct().ToDictionary(x => x, x => x);

EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String> would provide a much better fit for your situation:

C#
var res = new HashSet<string>(list);
if (res.Contains("string1"))
 
Share this answer
 
First off, don't create lists of object - it defeats the purpose of Generic Collections, which is strong typing. Use a list of your actual class type, or a var if this is returned by a Linq request.

Then just use the ToDictionary Linq method: http://msdn.microsoft.com/en-us/library/bb549277(v=vs.95).aspx[^]

C#
List<MyClass> mylist = new List<MyClass> {
           new MyClass(){Id = 208, Subject = "some text"},
           new MyClass(){Id = 209, Subject = "another text"},
           new MyClass(){Id = 210, Subject = "one text"},
           new MyClass(){Id = 211, Subject = "text mix"}};
Dictionary<int, MyClass> dict = mylist.ToDictionary(m => m.Id);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900