将字符串列表添加到字典中的不同键

时间:2019-10-14 05:05:50

标签: c# dictionary

我有一个随机字符串(键)及其ASCII总和(值)的字典。由此,我想创建一个新的包含不同ASCII和的字典,以及一个与ASCII和匹配的所有字符串的列表。

我试图列出唯一的ASCII和,并使用它来访问字典。

    private void LoadFile_Click(object sender, EventArgs e)
    {
        //locate file with OpenFileDialog
        OpenFileDialog of = new OpenFileDialog(); //create new openfile dialog

        //save file path
        if (of.ShowDialog() == DialogResult.OK)
        {
            path = of.FileName;
            label1.Text = path.ToString();
        }

        //using streamreader and read to end, load entire contents
        //of file into a string
        using (StreamReader sr = new StreamReader(path))
        {
            _text = sr.ReadToEnd();
        }

        //seperate massive string by newline or carriage returns
        string[] words = _text.Split('\r', '\n');


        //tolist this array of strings 
        List<string> Word = words.ToList();

        //remove all white spaces or empty lines
        Word.RemoveAll(w => w == "");

        //produce a Dictionary keyed by each line chars
        //value is the ASCII sum of the chars

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

        dict = Word.ToDictionary(key => key, value => value.Sum(x => x));

        //key is the sum, value is all the strings that have that sum
        Dictionary<int, List<string>> _Distinct = new Dictionary<int, List<string>>();

        List<int> uniqueSums = new List<int>();


        uniqueSums = dict.Values.Distinct().ToList();

        foreach (int item in uniqueSums)
        {
            dict.Where(x => x.Value == item).ToList();
        }

        Console.Read();

    }

2 个答案:

答案 0 :(得分:1)

这可能是您要寻找的,产生一个Dictionary<int,List<string>>

var results = dict.GroupBy(x => x.Value)
                  .ToDictionary(x => x.Key, x => x.Select(y => y.Key).ToList());

注意 ToLookup可能是您所需的更简洁的解决方案。要了解它们之间的区别,请查看以下

What is the difference between LINQ ToDictionary and ToLookup

答案 1 :(得分:0)

我想提供一些您不需要的改进...我假设您实际上不需要此方法之外的_text值。然后,您可以做...(免责声明,已通过我的手机完成,因此我无法进行检查)

    private void LoadFile_Click(object sender, EventArgs e)
    {
        // dialogs are IDisposable, so use a using block
        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return; // deal with if they don't press Ok
            }

            // FileName is already a string you don't need to use .ToString on it
            path = openFileDialog.FileName;
            label1.Text = path;
        }

        var results = File.ReadLines(path)
            .Where(line => string.IsNullOrWhiteSpace(line)==false)
            .ToDictionary(key => key, value => value.Sum(x => x))
            .GroupBy(x => x.Value)
            .ToDictionary(x => x.Key, x => x.Select(y => y.Key).ToList());      

        Console.Read();            
    }

另一个提示:对于dictuniqueSums,您的代码创建该类型的实例,然后在下一行中,通过将变量分配给其他内容来丢弃它。