2

I'm a little bit confused by the explanations of linq online so I figured I'd make a thread.

I want to replace my foreach statements with linq statements as I'm sure doing little things like this will make me program better.

Example of what I'd like to use LINQ with:

 public bool CheckForAccount(int accountID)
        {
            bool status = false;

            foreach (AccountHolders accountHolder in AccountHoldersList)
            {
                if (accountHolder.AccountNumber == accountID)
                {
                    status = true;
                    break;
                }
            }
            return status;
        }

Please can you provide an explanation of how it works too so I understand what you're doing.

Thanks in advance!

Zain
  • 1,106
  • 4
  • 12
  • 26

2 Answers2

6

So probably the most succinct statement would be:

public bool CheckForAccount(int accountId)
{
    return this.AccountHolderList.Any(x => x.AccountNumber == accountId);
}

In English this says

Check AccountHolderList for any cases where the AccountNumber property is equal to accountId. If there are any, return true, otherwise return false.

dav_i
  • 25,285
  • 17
  • 94
  • 128
0

both

AccountHolderList.Any(x => x.AccountNumber == accountId);

and

AccountHoldersList.Exists(p => p.AccountNumber == accountId);

work equally well. Here is a more in-depth explanation of the differences: Linq .Any VS .Exists - Whats the difference?

You could also use this:

  var match = AccountHolderList.FirstOrDefault(x => x.AccountNumber == accountId);
  return match != null ? true : false;

if you want to get a reference to the match as well. This works assuming accountId is unique

Community
  • 1
  • 1
Mr Balanikas
  • 1,489
  • 13
  • 24
  • 1
    `return match != null ? true : false;` can be replaced just by `return match != null;`. It currently reads "if match not equal to null returns true return true otherwise return false" – dav_i Apr 15 '14 at 09:47