Question

Let's assume I have a list and want to run a method only one time if the program enters the foreach. But important thing is initially I don't know if the loop empty or not. What is the best practice to run a code snippet only one time inside foreach loop?

List<int> dummy = new List<int> {1, 2, 3, 4, 5};

int sum = 0;
foreach (int i in dummy)
{
    sum += i;

    DoJob(); //this method must run only once
}

I tried this but it did not look well

List<int> dummy = new List<int> {1, 2, 3, 4, 5};

int sum = 0;
foreach (int i in dummy)
    sum += i;

if (dummy.Count>0)
    DoJob();

Do you have any better idea?

Était-ce utile?

La solution

Does it have to be inside the loop? From what you've posted, it doesn't seem to.

List<int> dummy = new List<int> {1, 2, 3, 4, 5};

if(dummy.Any())
    DoJob();

int sum = 0;
foreach (int i in dummy)
    sum += i;

Also, I'm assuming that snippet is just an example and not your actual code... if it is your actual code, you can use Sum (e.g., int sum = dummy.Sum();) instead of a foreach loop.

I'm also assuming your actual code uses an actual List<T> or some other concrete collection type. If it uses an IEnumerable, then the code above will iterate through the enumerable twice, which isn't recommended. If the enumerable actually represents a database query, you'll hit the database twice. So, if that's the case, just materialize the enumerable by calling .ToList first.

Autres conseils

If using linq

        if (dummy != null && dummy.Any())
        {
            DoJob();
        }

If not using linq

        if (dummy != null &&  dummy.Count > 0)
        {
            DoJob();
        }

C# specification clearly states purpose of foreach statement (8.8.4 The foreach statement):

foreach (type identifier in expression) embedded-statement

The foreach statement enumerates the elements of a collection, executing an embedded statement for each element of the collection.

So, if you want something to be executed for each element of the collection, then put it in the embedded statement. If you want something to be executed only once, then putting it in a statement which executes for each element of the collection, and trying to avoid running it for each element - not very good idea.

Your last sample looks completely OK to me. Just remove braces (matter of taste though).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top