We help IT Professionals succeed at work.

iterate List and check (shorter syntax)

Mutsop
Mutsop asked
on
Is there a shorter way to be writing the following (just out of curiosity):
public void AddCard(Card card)
        {
            Int32 Count = 1;
            foreach (Card item in _Cards)
            {
                if (item.Type != Type.Resource)
                {
                    if (item.Id == card.Id)
                    {
                        Count += 1;
                    }
                }
            }
            if (Count == _MAXIMUMAMOUNTCARD)
            {
                throw new Exception("You reached the maximum amounts of that card!");
            }
            _Cards.Add(card);
        }

Open in new window


As it seems kind of much. Maybe some equals?
Comment
Watch Question

Freelance programmer / Consultant
Commented:
This is less typing

public void AddCard(Card card)
        {
            Int32 Count = 1;
            foreach (Card item in _Cards)
            {
                if ((item.Type != Type.Resource) && (item.Id == card.Id))
                        Count ++;
            }
            if (Count == _MAXIMUMAMOUNTCARD)
            {
                throw new Exception("You reached the maximum amounts of that card!");
            }
            _Cards.Add(card);
        }
since you are using a counter you can use a for loop instead... and avoid brackets for one liner blocks:

Try this : (correct minor syntax errors if any, wrote this one in notepad)

public void AddCard(Card card)
        {

	for(int i=0,count=1; count<_MAXIMUMAMOUNTCARD; i++)
		if(_Cards.Cards[i].Type!= Type.Resource && _Cards.Cards[i].Id == card.Id)
			count++;

        if (Count == _MAXIMUMAMOUNTCARD)
                throw new Exception("You reached the maximum amounts of that card!");

        _Cards.Add(card);
        }

Open in new window