我有从reportData
private IDictionary<Guid, JobStatistic> GetAgentsStatistics(IList<Guid> agentIds)
{
var agentReportItems = from data in reportData
from agentId in data.AgentIds
where agentIds.Contains(agentId)
group data by agentId;
...
}
但是如果agentIds是一个空集合怎么办?如何检查这种情况?
答案 0 :(得分:2)
var agentReportItems = from data in reportData
from agentId in data.AgentIds
where agentIds != null && agentIds.Contains(agentId)
group data by agentId;
只检查它是否为空,如果不是,则按原样使用它。
答案 1 :(得分:2)
您发布的逻辑将适用于空集合&#39;
但是,假设您的意思是null而不是&#39;空&#39;,这就是ArgumentNullException的用途。
Throwing ArgumentNullException
private IDictionary<Guid, JobStatistic> GetAgentsStatistics(IList<Guid> agentIds)
{
if (agentIds == null)
throw new ArgumentNullException("agentIds"); // use nameof(agentIds) instead of "agentIds" if using C# 6 or later
var agentReportItems = from data in reportData
from agentId in data.AgentIds
where agentIds.Contains(agentId)
group data by agentId;
//...
}
答案 2 :(得分:0)
您可以使用.Any()
if (!agentIds.Any()) //It's empty.
{
throw new ArgumentException("agentIds cannot be empty.");
}
请注意&#39; null&#39;并不意味着列表是空的。 Null将完全没有列表。