Linq聚合词典成新词典

时间:2017-02-22 17:45:53

标签: c# linq

class Key { string s; int i; }

给定Dictionary<Key,int>我想要一个新的Dictionary<string,int>,它是所有键上每个Key.s的最小字典值的映射。

我觉得这应该很容易,但我无法得到它。

由于

澄清:

var dict = new Dictionary<Key,int>();
dict.Add(new Key("a", 123), 19);
dict.Add(new Key("a", 456), 12);
dict.Add(new Key("a", 789), 13);
dict.Add(new Key("b", 998), 99);
dict.Add(new Key("b", 999), 11);

我想制作字典:

 "a" -> 12
 "b" -> 11
希望有所帮助。

2 个答案:

答案 0 :(得分:3)

我并不清楚您正在尝试做什么,但您可以使用.Select(...和/或.ToDictionary(...

例如:

Dictionary<Key, int> original = ...
Dictionary<string, int> mapped = original.ToDictionary((kvp) => kvp.Key.s, (kvp) => kvp.Key.i);

如果你的问题更清楚,我会改进我的答案。

编辑:(问题已澄清)

var d = dict.GroupBy(kvp => kvp.Key.s).ToDictionary(g => g.Key, g => g.Min(k => k.Value));

您希望按键s属性进行分组,然后选择字典值的最小值作为新词典值。

答案 1 :(得分:1)

一种更通用的方法,可以跳过num = 1 for line in pdb_file: num += 1 if "L01" in line: print num break pdb_file.seek(0) # go back to the beginning and then it can be iterated again last_host=int(num) print(last_host-1) for atom in range(0, last_host-1): data = pdb_file.readline() new_pdb_file.write(data) 创建的Lookup

.GroupBy

样品使用:

    public static Dictionary<K, V> aggregateBy<T, K, V>(
        this IEnumerable<T> source,
        Func<T, K> keySelector,
        Func<T, V> valueSelector,
        Func<V, V, V> aggregate,
        int capacity = 0,
        IEqualityComparer<K> comparer = null)
    {
        var dict = new Dictionary<K, V>(capacity, comparer);
        foreach (var t in source)
        {
            K key = keySelector(t);
            V accumulator, value = valueSelector(t);
            if (dict.TryGetValue(key, out accumulator))
                value = aggregate(accumulator, value);
            dict[key] = value;
        }
        return dict;
    }