'How to return multiple keyvalue pairs in c# using foreach loop? [duplicate]
Currently I have written a logic to return multiple key value pairs using for each loop, but it's return just the first key-value pair. My current code is:
public static string ReturnData(IEnumerable<KeyValuePair<string, string>> abc)
{
if (abc != null)
{
foreach (KeyValuePair<string, string> item in abc)
{
return $"{{\"{item.Key}\":\"{item.Value}\"}}";
}
return null;
}
}
Solution 1:[1]
You can use an iterator block to return a list of items
public static IEnumerable<string> ReturnData(IEnumerable<KeyValuePair<string, string>> abc)
{
if (abc != null)
{
foreach (KeyValuePair<string, string> item in abc)
{
yield return $"{{\"{item.Key}\":\"{item.Value}\"}}";
}
}
}
Solution 2:[2]
Use Enumerable.Select extension:
abc.Select(item => $"{{\"{item.Key}\":\"{item.Value}\"}}");
If you still want to re-use this code, then re-write ReturnData like this:
public static IEnumerable<string> ReturnData(this IEnumerable<KeyValuePair<string, string>> abc)
{
if (abc != null)
{
return abc.Select(item => $"{{\"{item.Key}\":\"{item.Value}\"}}");
}
return Enumrable.Empty<string>();
}
Note, that this turns ReturnData into an extension method, which allows to call it this way:
abc.ReturnData();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TylerH |
| Solution 2 |
