2014-03-19 42 views

回答

2

您可以尝试的LINQ找到按键的交集:

Boolean hasSameKeys = 
    (dict1.Keys.Select(x => new DateTime(x.Year, x.Month, 1)).Intersect(
    dict2.Keys.Select(x => new DateTime(x.Year, x.Month, 1)))).Any(); 

如果你想检查是否有年份和月份在字典中,你可以再次使用Linq:

int month = 3; // <- Month of interest 
    int year = 2014; // <- Year of interest 
    Boolean hasKeys = dict1.Keys.Where(x => (x.Year == year) && (x.Month == month)).Any(); 

如果您想要汇总您的数据,例如总结值内每个月

Dictionary<DateTime, int> oldDict = new Dictionary<DateTime, int>() { 
    {new DateTime(1999, 1, 25), 1}, 
    {new DateTime(1999, 2, 25), 2}, // <- These values should be added up 
    {new DateTime(1999, 2, 27), 3}, // <- These values should be added up 
    {new DateTime(1999, 3, 25), 4}, 
    {new DateTime(1999, 4, 25), 5}, 
    }; 

    Dictionary<DateTime, int> aggregatedDict = 
    oldDict.GroupBy(pair => new DateTime(pair.Key.Year, pair.Key.Month, 1), 
        pair => pair.Value) 
      .ToDictionary(x => x.Key, 
         x => x.Aggregate(0, (sum, item) => sum + item)); 
+0

如果我想检查字典中是否存在某个月份,那该怎么办?如果是这样更新数据。否则将日期添加到字典中? – user3305453

+0

@ user3305453:你可以在字典键上使用Linq,看看我的编辑 –

+0

我真的需要一些更大的帮助。我有一些DateTime的数据。现在我必须按年,月,日等向用户表示数据。所以我必须预先计算所有的值。你能帮我解决这个问题吗? – user3305453

0

将您DateTimeString只有年份和月份保持在它:

String dateString = DateTime.Now.ToString("yyyyMM"); 

然后,所有你需要做的是一个简单的字符串比较。

0

我几乎更喜欢用linq。在这种情况下Linq的Any方法。

 var month = 3; 
     var year = 2014; 

     var dic1 = new Dictionary<int, DateTime>(); 
     var dic2 = new Dictionary<int, DateTime>(); 

     // fill dictionaries 

     if (dic1.Any(date => date.Value.Year == year && date.Value.Month == month) && 
      dic2.Any(date => date.Value.Year == year && date.Value.Month == month)) 
     { 
      // do something 
     } 
相关问题