0

I have the algorithm that select a data from collection of 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;
 ...
}

But what if agentIds is an empty collection? How to check this situation?

Anatoly
  • 1,908
  • 4
  • 25
  • 47

3 Answers3

2
 var agentReportItems = from data in reportData
                        from agentId in data.AgentIds
                        where agentIds != null && agentIds.Contains(agentId)
                        group data by agentId;

Just check if it's null, and if it's not, then use it as you already did.

Jashaszun
  • 9,207
  • 3
  • 29
  • 57
2

The logic you've posted will work for an 'empty collection'

However, assuming you meant null instead of 'empty', this is what an ArgumentNullException would be used for.

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;
    //...
}
Community
  • 1
  • 1
Wyatt Earp
  • 1,783
  • 13
  • 23
0

You can quickly check if an enumerable is empty using .Any()

if (!agentIds.Any()) //It's empty.
{
    throw new ArgumentException("agentIds cannot be empty.");
}

Be aware that 'null' does not mean the list is empty. Null would be a complete absence of the list.

PhonicUK
  • 13,486
  • 4
  • 43
  • 62