Reputation: 3
I have a dictionary of random strings (key), and their ASCII sum(value). From this, I want to create a new dictionary of distinct ASCII sums, and a List of all strings that match the ASCII sum.
I have attempted making a List of the unique ASCII sums and accessing my dictionary with that.
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();
}
Upvotes: 0
Views: 117
Reputation: 81493
This might be what you are looking for, produces a Dictionary<int,List<string>>
var results = dict.GroupBy(x => x.Value)
.ToDictionary(x => x.Key, x => x.Select(y => y.Key).ToList());
Note ToLookup
is probably a more succinct solution for what you need. To know the difference, take a look at the following
What is the difference between LINQ ToDictionary and ToLookup
Upvotes: 1
Reputation: 5763
I'd like to offer some improvements that you didn't ask for... I'm assuming that you don't actually need the value of _text
outside this method. Then you can do... (Disclaimer, done from my phone, so I can't check this)
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();
}
One other tip: for dict
and uniqueSums
, your code creates an instance of that type, and the very next line, you throw it away by assigning the variable to something else.
Upvotes: 0