简体   繁体   English

C#如何将列表添加到字典

[英]C# How to add a list to a dictionary

I'm trying to make a histogram using a dictionary. 我正在尝试使用字典制作直方图。 I started off with a giant string that I then converted to an array of strings, and then a list. 我从一个巨大的字符串开始,然后将其转换为字符串数组,然后转换为列表。 From there I need need to make a histogram directory that takes my string list. 从那里,我需要创建一个包含我的字符串列表的直方图目录。

I don't have much already because I only just started and am just starting to learn about Dictionaries. 我还没有太多,因为我才刚刚开始并且才刚刚开始学习字典。

static void Main(string[] args)
        {
            string Speach;
            Speach = "I say to you today, my friends, so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream. " +
            "I have a dream that one day this nation will rise up and live out the true meaning of its creed: We hold these truths to be self-evident: that all men are created equal. " +
            "I have a dream that one day on the red hills of Georgia the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood. " +
            "I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice. " +
            "I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. " +
            "I have a dream today. I have a dream that one day, down in Alabama, with its vicious racists, with its governor having his lips dripping with the words of interposition and nullification; one day right there in Alabama, little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers. " +
            "I have a dream today. I have a dream that one day every valley shall be exalted, every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight, and the glory of the Lord shall be revealed, and all flesh shall see it together. " +
            "This is our hope. This is the faith that I go back to the South with. With this faith we will be able to hew out of the mountain of despair a stone of hope. With this faith we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. " +
            "With this faith we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day. " +
            "This will be the day when all of God's children will be able to sing with a new meaning, My country, 'tis of thee, sweet land of liberty, of thee I sing. Land where my fathers died, land of the pilgrim's pride, from every mountainside, let freedom ring. " +
            "And if America is to be a great nation this must become true. So let freedom ring from the prodigious hilltops of New Hampshire. Let freedom ring from the mighty mountains of New York. Let freedom ring from the heightening Alleghenies of Pennsylvania! " +
            "Let freedom ring from the snowcapped Rockies of Colorado! Let freedom ring from the curvaceous slopes of California! But not only that; let freedom ring from Stone Mountain of Georgia! " +
            "Let freedom ring from Lookout Mountain of Tennessee! Let freedom ring from every hill and molehill of Mississippi. From every mountainside, let freedom ring. " +
            "And when this ha   ppens, when we allow freedom to ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual, Free at last! free at last! thank God Almighty, we are free at last!";

            string[] SpeachSplit = Speach.Split();
            List<string> SpeachList = SpeachSplit.OfType<string>().ToList();

            Dictionary<string, int> Historgram = new Dictionary<string, int>();

//This is where I get confused??
            for (var i = 0; i < SpeachList.Count; i++)
            {
                Historgram.Add(SpeachList[i],//? );
            }

            Console.ReadLine();

My question is, how do I add my string list to my dictionary while keeping my dictionary with my string key and int value? 我的问题是,如何在将字典与字符串键和整数值保持一致的同时,将字符串列表添加到字典中?

If I understand correctly what you are trying to achieve, this solution should work: 如果我正确理解您要实现的目标,则此解决方案应该有效:

string[] SpeachSplit = Speach.Split();
Dictionary<string, int> Historgram = new Dictionary<string, int>();

// loop through all words
for (var i = 0; i < SpeachSplit.Length; i++)
{
    string word = SpeachSplit[i];
    // check if your word is already in the dictionary
    if(!Historgram.ContainsKey(word))
    {
        // if it is not in the dictionary, add it to dictionary with 0 occurrences
        Historgram.Add(word, 0);
    }
    // add one to the number of occurrences
    Historgram[word]++;
}
// at this point dictionary contains words as keys and number of occurrences as value

Basically this 基本上这个

  1. Splits by space 按空间分割
  2. Converts to lower case 转换为小写
  3. Uses regex to replace all non alphanumerics 使用正则表达式替换所有非字母数字
  4. Groups and Counts 组和计数
  5. Projects to a Dictionary 项目到字典

Code

var result = Speach.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                   .Select(x => x.ToLower()))
                   .Select(x => Regex.Replace(x, "[^a-zA-Z0-9-]", ""))
                   .GroupBy(x => x)
                   .ToDictionary(x => x.Key, x => x.Count());

Full Demo here 完整的演示在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM