【问题标题】:How do I add multiple values to one key in a dictionary and display the duplicates? [duplicate]如何将多个值添加到字典中的一个键并显示重复项? [复制]
【发布时间】:2019-02-09 22:18:00
【问题描述】:

我正在处理一个包含公会名称列表的输入文件,然后是这些公会名称的公会服务器。我的问题是,对于某些公会存在重复,这意味着相同的公会存在于不同的服务器上。所以我需要从我的输入文件中读取的 guildName 来显示它所在的不同服务器。这是我到目前为止的代码:

private void buildGuilds()
    {
        using (StreamReader inFile = new StreamReader("guilds.txt"))
        {
            string str = null;
            char[] delimiters = {'-', '\t'};

            //while the buffer isn't empty
            while ((str = inFile.ReadLine()) != null)
            {
                SortedList<string, string> guild = new SortedList<string, string>();
                string[] Buffer = str.Split(delimiters);
                guildName = Buffer[1];
                guildServer = Buffer[2];


                    if (!dictGuilds.ContainsKey(guildName))
                    {
                        dictGuilds.Add(guildName, new List<string>());
                    }
                    dictGuilds[guildName].Add(guildServer);

所以我的程序将数据读入 2 个变量,然后确定哪些值在哪里,但是在使用传统的 foreach pair.Key pair.Value 方法时我无法打印它。这也是我的打印方法。

private void printGuilds()
    {
       foreach (KeyValuePair<string, List<string>> pair in dictGuilds)
        {
            Guilds_List.Items.Add(pair.Key + pair.Value);
        }
    }

我能得到的任何帮助都会很棒。非常感谢你

【问题讨论】:

标签: c#


【解决方案1】:

我认为以下内容可能是您正在寻找的内容,尽管我不确定您想要做什么(如果我遗漏了什么,请随时告诉我)。

我通过以下方式实现了以下目标:

  • 创建一个空的类库项目
  • 添加 xunitfluentassertions nuget 包。

这允许您运行验证此断言的单元测试。

如果我误解了这个问题,请告诉我,我会尽力为您调整。请注意,为了编写测试和验证内容,我从文件输入中更改了输入。

using System.Collections.Generic;
using System.IO;
using System.Linq;
using FluentAssertions;
using Xunit;

namespace MultiValueDictionaryTests
{
    public class MultiValueDictionaryTests
    {
        [Fact]
        public void UnderstandsPairsCorrectly()
        {
            /* Mimics the following file contents:
             Guild1-ServerDEF
             Guild2-ServerDEF
             Guild2-ServerABC
             Guild1 ServerXYZ
             Guild2-ServerABC
             Guild2-ServerABC
             */
            var testString = "Guild1-ServerDEF\r\nGuild2-ServerDEF\r\nGuild2-ServerABC\r\nGuild1\tServerXYZ\r\nGuild2-ServerABC\r\nGuild2-ServerABC\r\n";

            var builder = new GuildBuilder();

            var result = builder.BuildGuilds(testString);

            result.Should().ContainKey("Guild1");
            result.Should().ContainKey("Guild2");

            result["Guild1"].Should().ContainKey("ServerDEF")
                .And.ContainKey("ServerXYZ");
            result["Guild1"].Should().NotContainKey("ServerABC");

            result["Guild2"].Should().ContainKey("ServerDEF")
                .And.ContainKey("ServerABC");

            result["Guild2"].First().Key.Should().Be("ServerABC");
        }

        [Fact]
        public void WriteLine_ShowsCommaSeparatedValues()
        {
            var builder = new GuildBuilder();

            var example = new SortedDictionary<string, SortedList<string, string>>
            {
                {
                    "Guild1", new SortedList<string, string> {{"ServerABC", "ServerABC"}, {"ServerDEF", "ServerDEF"}}
                },
                {
                    "Guild2", new SortedList<string, string> {{"ServerABC", "ServerABC"}, {"ServerXYZ", "ServerXYZ"}}
                }
            };

            List<string> resultLines = builder.WriteGuildLines(example);

            resultLines.First().Should().Be("Guild1 - ServerABC, ServerDEF");
            resultLines.Last().Should().Be("Guild2 - ServerABC, ServerXYZ");
        }
    }

    public class GuildBuilder
    {
        readonly char[] delimiters = { '-', '\t' };

        public SortedDictionary<string, SortedList<string,string>> BuildGuilds(string inputString) // instead of file
        {
            var result = new SortedDictionary<string, SortedList<string,string>>();
            using (var reader = new StringReader(inputString))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    var splitArray = line.Split(delimiters);
                    var guild = splitArray[0];
                    var server = splitArray[1];

                    if (!result.ContainsKey(guild))
                    {
                        result.Add(guild, new SortedList<string,string>());
                    }

                    if (!result[guild].ContainsKey(server))
                    {
                        result[guild].Add(server, server);
                    }

                }
            }

            return result;
        }

        public List<string> WriteGuildLines(SortedDictionary<string, SortedList<string, string>> input)
        {
            var result = new List<string>();

            foreach (var item in input)
            {
                result.Add($"{item.Key} - {string.Join(", ", item.Value.Keys)}");
            }

            return result;
        }
    }
}

【讨论】:

  • OP 已经有代码来为每个键构建值列表...我相信他们正在询问使用 WriteLine 显示列表。
  • @AlexeiLevenkov 的评论对我来说很有意义;我已经更新了我的示例以尝试包含执行此操作的方法,但同意 OP 可能希望查看 cmets 中的这些链接或澄清问题。
猜你喜欢
  • 2022-01-18
  • 2021-04-30
  • 1970-01-01
  • 2018-08-14
  • 2011-03-13
  • 2011-04-16
  • 2015-02-16
  • 2014-04-13
  • 1970-01-01
相关资源
最近更新 更多