Click here to Skip to main content
15,890,995 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do i return a key value pair, where the function returns List<strings>.
The method is returning a list of string fetch from the database, now i want it to return it as key value pair instead of list of only values from the database.

What I have tried:

C#
public List<string> GetLanguagesForMobile()
        {
            var result = _translationService.GetLanguagesForMobile();
            return result.Distinct().ToList();         
        }

Reponse:-
[
  "en",
  "es"
]

Required as:-
{ "english":"en",
"spanish":"es"}
Posted
Updated 27-Feb-18 2:57am
v2
Comments
phil.o 27-Feb-18 8:03am    
Where would "english" and "spanish" values come from? Are they stored in the database along with "en" and "es" respectively?
Avinash Gupta 27-Feb-18 8:54am    
No,It has to be hard coded
Karthik_Mahalingam 27-Feb-18 9:13am    
hardcoded in a variable?
show the code
Avinash Gupta 27-Feb-18 9:18am    
I want it to be a key for each returning value
Karthik_Mahalingam 27-Feb-18 9:21am    
what is the value you are getting in result.Distinct().ToList();
and show how you are storing the mapping

1 solution

You can't return a key value pair, or a list of key value pairs from a method that is set up to return a list of strings - C# is strongly typed, and checks parameter types!

You can change the method return a list of key value pairs:
C#
List<KeyValuePair<string, string>> GetLanguagesForMobile()
   {
   ...
   }
Or a Dictionary:
C#
Dictionary<string, string> GetLanguagesForMobile()
   {
   ...
   }
And recode the method to generate the appropriate data - but if you declare a method as returning a type, you can only return that type or types derived from it.
 
Share this answer
 
Comments
PIEBALDconsult 27-Feb-18 8:58am    
It can return a snippet of XML or CSV. :D But that seems beyond the abilitites of the OP.
OriginalGriff 27-Feb-18 9:04am    
Or JSON, or ...
But yes - that's why I tried to explain why it wasn't going to work!
At least changing the signature will force him to look at the stuff using the method already.

Do you think I should have suggested a list of tuples? :laugh:
Richard MacCutchan 27-Feb-18 9:38am    
How about a List of Dictionaries of Lists of Tuples?

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