需要从多个词典<datetime,double> </datetime,double>获取唯一的键集

时间:2012-09-12 19:21:49

标签: c# linq dictionary contains hashset

我有20个<Datetime,double>字典,主要是针对相同的日期范围(例如2012年6月24日至2012年6月4日)。有些词典有额外的天数,有些则缺少天数。我想要一个使用所有唯一日期的数组。

目前,我正在遍历所有密钥并添加到哈希集以获取唯一集合,然后将哈希集转换为数组。有更有效的方法吗?

对于记录,我还考虑迭代并使用字典的containsKey函数并添加到列表或LINQ。我现有的流程似乎可以解决问题。

3 个答案:

答案 0 :(得分:6)

您描述的代码是您可以获得的最有效的代码 使用LINQ:

可以用更少的代码(和类似的效率)来实现
dicts.SelectMany(d => d.Keys).Distinct().ToArray();

答案 1 :(得分:0)

你可以将所有词典拉到允许“密钥重复”的列表中,然后使用Distinct功能:

        Dictionary<DateTime, double> dic = new Dictionary<DateTime, double>()
        {
            {DateTime.Now, 111}
        };

        Dictionary<DateTime, double> dic2 = new Dictionary<DateTime, double>()
        {
            {DateTime.Now, 111}
        };

        var list = dic.ToList();
        list.AddRange(dic2.ToList());

        var final = list.Distinct().ToDictionary(x => x.Key, x => x.Value);

答案 2 :(得分:0)

我在寻找一个稍微不同的问题的解决方案时发现了这篇文章,但是使用了接受的答案作为我的解决方案的基础,所以我认为有同样问题的人也可能会走这条路。

我一直在寻找一种方法来查找一组对象中的单个属性,这些属性在每个对象的属性集中都是唯一的。我在字典中有属性名称,我想要一个只出现在一个字典中的键列表。

这是我的解决方案,您应该只能将其粘贴到linqpad中以使其正常工作。

void Main()
{
  var d = new Dictionary<string, Dictionary<string, string>>
        {
            {
                "First",
                new Dictionary<string, string>
                {
                    {"A", "ash"},
                    {"B", "brett"},
                    {"R", "ripley"},
                    {"J", "jones"},
                    {"D", "dallas"}
                }
            },
            {
                "Second",
                new Dictionary<string, string>
                {
                    {"A", "ash"},
                    {"B", "brett"},
                    {"R", "ripley"},
                    {"D", "dallas"},
                    {"K", "kane"}
                }
            },
            {
                "Third",
                new Dictionary<string, string>
                {
                    {"A", "ash"},
                    {"B", "brett"},
                    {"R", "ripley"},
                    {"D", "dallas"},
                    {"V", "vasquez"}
                }
            },
            {
                "Fourth",
                new Dictionary<string, string>
                {
                    {"A", "ash"},
                    {"B", "brett"},
                    {"R", "ripley"},
                    {"D", "dallas"},
                    {"H", "hicks"}
                }
            }
        };

var u = d.Values.SelectMany(x => x.Keys).Distinct().Where(y => d.Values.SelectMany(z => z.Keys).Count(a => a == y) == 1).ToArray();

        foreach (var f in u)
        {
            Console.WriteLine("{0} => {1}", f, d.Keys.Single(s => ((Dictionary<string, string>)d[s]).ContainsKey(f)));
        }

}

相关问题