[英]Check if two dictionaries having a DateTime key share the same Date
我有兩個字典。 我在指定的時間存儲值。 現在我想在處理它時更加細化。 我想比較一下兩個字典是否具有相同的月份和年份,而與日期無關。 我怎么可能那樣做。
您可以嘗試使用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));
將您的DateTime
轉換為僅保留年份和月份的String
:
String dateString = DateTime.Now.ToString("yyyyMM");
然后,您要做的只是一個簡單的字符串比較。
我幾乎喜歡使用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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.