Possible Multiple Enumeration of IEnumerable. How to solve? Do I need to solve?

c#, ienumerable

Solution

The possible problem depends on where your `IEnumerable` comes from. Some data sources might only allow for a single enumeration or they might be expensive (maybe some database query), which would be already started by `attributeList.Any()`.

You can just remove the `Any()` check, because if there are no elements in your `IEnumerable` , your loop won't run anyway (assuming your example shows the complete picture and there is no other logic dependent on the check).

EDIT: Based on your edited question, you cannot remove the check. But, you can use `attributeList.ToArray()` to convert your `IEnumerable` to an array which you then work with and get rid of the warning.

Problem

I have the following code which gives the warning in the title. I am pretty sure I have done something like this before but it didnt give any warning. I would like to ask two things of those posting. 1) What here would cause a problem? 2) Does it need to be fixed? The reason I ask is that this code works fine as I expect it to so clearly this warning is not causing an issue. I cannot stand to have warnings etc in my code though and so would like a solution to this but I also want to know why this warning occurs and if it is harmful in any way. Code: ``` public class AttributeType { private string m_attributeNameField; public string AttributeName { get { return m_attributeNameField; } set { m_attributeNameField = value; } } } private StandardResponseType ValidateAttributes(string featureType, IEnumerable<AttributeType> attributeList, string userCategory) { StandardResponseType standardResponse = new StandardResponseType(DateTime.Now.ToString(CultureInfo.InvariantCulture), "RWOL_UTILS.Get_Item_Attributes", "", "OK"); if (attributeList.Any()) { foreach (AttributeType attribute in attributeList) { if (attribute.AttributeName == null) continue; { //do stuff } } } else { standardResponse.Message = "Error: No attributes passed in the list. ValidateAttributes()."; standardResponse.ResponseCode = "FAIL"; return standardResponse; } } ``` EDIT: There is more code in the method but it doesn't have a bearing on this issue. UPDATE: I had to add the follwing code to make this work. Why is it more efficient to add this? If I have to count and read the new list then what is the difference between doing that and doing it on the original item? The list is only ever passed once. I could understand this issue if the list was populated within the method but is isnt. It is just passed in already filled. ``` List<AttributeType> newlist = attributeList.ToList(); if (newlist.Count() != 0) { foreach (AttributeType attribute in newlist) ............ ```

Original source