如何使用foreach循环返回C#中的多个键值对?

发布于 2025-01-24 03:33:42 字数 454 浏览 4 评论 0原文

目前,我已经编写了逻辑,以使用每个循环返回多个键值对,但它只是返回的第一个键值对。 我当前的代码是:

 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;
            }
         }

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 
quot;{{\"{item.Key}\":\"{item.Value}\"}}";
                 }
            return null;
            }
         }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜妞爱困 2025-01-31 03:33:42

您可以使用 iterator block 返回项目列表

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}\"}}";
        }
    }
}

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 
quot;{{\"{item.Key}\":\"{item.Value}\"}}";
        }
    }
}
走过海棠暮 2025-01-31 03:33:42

使用 emumosit.Select.Select < < << /a>扩展名:

abc.Select(item => $"{{\"{item.Key}\":\"{item.Value}\"}}");

如果您仍然要重新使用此代码,则重新写returndata这样:

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

请注意, turn turn returndata进入扩展方法,该方法允许以这种方式调用:

abc.ReturnData();

Use Enumerable.Select extension:

abc.Select(item => 
quot;{{\"{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 => 
quot;{{\"{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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文