如何返回键值对,函数返回列表< strings> [英] How do I return a key value pair, where the function returns list<strings>
本文介绍了如何返回键值对,函数返回列表< strings>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何返回一个键值对,函数返回 List< strings>
。
该方法返回一个字符串列表从数据库中获取,现在我希望它将其作为键值对而不是数据库中的唯一值列表返回。
我尝试过:
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:
public List<string> GetLanguagesForMobile()
{
var result = _translationService.GetLanguagesForMobile();
return result.Distinct().ToList();
}
Reponse:-
[
"en",
"es"
]
Required as:-
{ "english":"en",
"spanish":"es"}
推荐答案
您无法返回键值对或键值列表从设置为返回字符串列表的方法对 - C#是强类型的,并检查参数类型!
您可以更改方法返回列表键值对:
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:
List<KeyValuePair<string, string>> GetLanguagesForMobile()
{
...
}
或字典:
Or a Dictionary:
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.
这篇关于如何返回键值对,函数返回列表< strings>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文