0
\$\begingroup\$

Looking to see if there is a simpler way to achieve this. I would love if I could keep the return as a one-line LINQ expression. I want to grab the total number of hints used, which can be more than one.

public int hintsUsed
{
 get
 {
 int i = 0;
 questions.ForEach(q => i += q.hintsUsed);
 return i;
 }
}
Heslacher
50.9k5 gold badges83 silver badges177 bronze badges
asked May 13, 2018 at 20:53
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

You can use the Sum function

public int HintsUsed => questions.Sum(q => q.hintsUsed);

By using an expression bodied member (since C# 6.0), you can even get rid of the get and the return keywords plus a few braces.

The code above is equivalent to

public int HintsUsed
{
 get
 {
 return questions.Sum(q => q.hintsUsed);
 }
}

Most of the LINQ-to-Objects functionality is provided by the Enumerable Class.

answered May 13, 2018 at 21:01
\$\endgroup\$
1
  • \$\begingroup\$ Ahh perfect, thank you. Sometimes its difficult to search for these things because I'm not sure which words to use. I will definitely use this in the future. \$\endgroup\$ Commented May 13, 2018 at 21:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.