我使用以下的“字典”:
Dictionary<DateTime, List<string>> dictionary
我该如何简单地检查一个类型为字符串的值的 List
是否为非空?
Dictionary<DateTime, List<string>> dictionary
我该如何简单地检查一个类型为字符串的值的 List
是否为非空?
尝试使用Linq:
Dictionary<DateTime,List<string>> dictionary = ...
bool hasNotEmptyValues = dictionary
.Any(pair => pair.Value != null && pair.Value.Any());
dictionary.Values.Any(list => list.Any())
还有一个问题,就是你如何看待list == null
的情况。
如果你想把它当作一个空列表处理,则:
dictionary.Values.Any(list => list?.Any() ?? false)
如果不是:
dictionary.Values.Any(list => list?.Any() ?? true)
var HasNonemptyList = dictionary.Values.Any(iList => iList.Count() > 0)
Any()
比 Count() > 0
更明确。如果是为了挤出最后一点性能,你可以使用本地的 List.Count
属性。 - huysentruitw
dictionary[yourDateTime].Any()
的意思是“字典[你的日期时间].有任何元素吗?” - oerkelens