[英]How to display results values of Dictionary<string, string> from a LINQ statement
I'm struggling and unable to display the results2
of my Dictionary<string, string> files
我挣扎,无法显示
results2
我的Dictionary<string, string> files
Dictionary<string, string> files = new Dictionary<string, string>();
foreach (var file in Directory.GetFiles(filepath + "\\Saved Pictures\\", "*.jpg"))
{
files.Add(file, CalculateHash(file));
}
var duplicates = files.GroupBy(item => item.Value).Where(group => group.Count() > 1);
var results2 = duplicates.Select(group => group.GroupBy(x => x.Value));
So far I have tried :到目前为止,我已经尝试过:
foreach (KeyValuePair<string, string> result in results2)
{
Console.WriteLine("Key: {0}, Value: {1}", result.Key, result.Value);
}
And I'm encountering this error message:我遇到了这个错误信息:
Cannot convert type 'System.Collections.Generic.IEnumerable<System.Linq.IGrouping<string, System.Collections.Generic.KeyValuePair<string, string>>>' to 'System.Collections.Generic.KeyValuePair<string, string>`
无法将类型“System.Collections.Generic.IEnumerable<System.Linq.IGrouping<string, System.Collections.Generic.KeyValuePair<string, string>>>”转换为“System.Collections.Generic.KeyValuePair<string, string>”
What I am doing wrong?我做错了什么?
The error message tells you exactly what's wrong.错误消息准确地告诉您出了什么问题。
results2
is not an IEnumerable<KeyValuePair<string, string>>
as you'd assume in the foreach
loop, but a more complex type, an IEnumrable<IGrouping<string, KeyValuePair<string, string>>>
. results2
不是您在foreach
循环中假设的IEnumerable<KeyValuePair<string, string>>
,而是更复杂的类型,即IEnumrable<IGrouping<string, KeyValuePair<string, string>>>
。
Two nested foreach
loops will do it:两个嵌套的
foreach
循环将执行此操作:
foreach (var grouping in results2)
{
foreach (var pair in grouping)
{
// pair is a KeyValuePair<string, string>
}
}
The more I look at this code the less I understand it.我看这段代码越多,对它的理解就越少。 What is the point of grouping already grouped values by the same property they were originally grouped by?
将已经分组的值按它们最初分组的相同属性分组有什么意义?
In plain English, I suspect you are simply trying to obtain a list of all sets of files with identical hashes.用简单的英语,我怀疑您只是想获取具有相同哈希值的所有文件集的列表。 A simple way to do this is:
一个简单的方法是:
var files = Directory.GetFiles(filepath + "\\Saved Pictures\\", "*.jpg");
// An enumerable of enumerables of files that share the same hash
var dupes = files.GroupBy(CalculateHash).Where(g => g.Count() > 1);
If you need to flatten this for display purposes, you can do:如果您需要将其展平以用于显示目的,您可以执行以下操作:
// IEnumerable<(string hash, string file)>
var flattened = dupes.SelectMany(grp => grp.Select(file => (hash: grp.Key, file)));
foreach ((var hash, var file) in flattened)
{
Console.WriteLine($"Key: {hash}, Value: {file}");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.