-1

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;
            }
         }
6
  • 2
    Change the method return type to IEnumerable<string> and add the yield keyword before return inside the foreach loop Commented Apr 26, 2022 at 11:49
  • Do away with this method entirely, and use whatever value you supply into abc directly wherever you use it Commented Apr 26, 2022 at 11:51
  • @CaiusJard how ? Commented Apr 26, 2022 at 12:11
  • 1
    Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the CC BY-SA 4.0 license). By SE policy, any vandalism will be reverted. Commented Apr 26, 2022 at 14:06
  • Somewhere else you have maybe var dict = new Dictionary<string, string>(){ ["a"] = "a" }; and you're calling foreach(string s in ReturnData(dict)) - just do foreach(string s in dict.Select(kvp => $"{{\"{item.Key}\":\"{item.Value}\"}}")) Commented Apr 26, 2022 at 16:11

2 Answers 2

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}\"}}";
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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();

1 Comment

Yea, and use it instead of ReturnData, rather than inside of ReturnData.. An $@ string with "" instead of \" might look cleaner

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.