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!

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

you are one second faster :) +1
Can you please explain what you're code is saying? thanks in advance
@user3245390 Updated to include description of code. Though it should be obvious from the code :)
well mine will also work now..:P but lots of downvotes got..:(
i was not aware of any() method and its working, today learned new thing from your answer..@dav_i
|
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

1 Comment

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.