3

I have a list of objects, of class Author, and I want to search this list of authors, based on one of the Author's properties, name, and when I receive a match I would like to return the instance of Author to be used to create an instance of another class, that requires Author as part of its constructor.

A better way to explain it would be:

author getAuthor(String arg_name)
{
  foreach (author auth in authorList)
  {
    if (auth.name == arg_name)
    {
      return auth;
    }
  }
}

Although I realize this specific code does work, is there a better way to perform this action?

0

3 Answers 3

8

You can use Enumerable.FirstOrDefault like:

return authorList.FirstOrDefault(a=> a.name == arg_name);

This would return null if any author with name doesn't matches with the parameter passed.

For your particular code, your check if (auth == arg_name) should give you compile time error. Your check should be if (auth.name == arg_name)

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

3 Comments

Works great! Much more compact than a foreach, thanks! Now to wait the 9 minutes to accept your answer :|
@sh3rifme, start using LINQ this would make your code compact and it is fun to work with :)
thanks for pointing that out! I keep meaning to use more LINQ but i'm only just getting started with C# and have needed a good resource to guide my newb self, i'll check that link (pun intended) out!
0

Assuming you have a public property of Name in the Author you should be able to to get its value and compare it to the requested value (in your case arg_name). One way is to use foreach:

foreach (author auth as authorList)
  {
    if (auth.name == arg_name)
    {
      return auth;
    }
  }

Another way is to use Linq:

return authorList.FirstOrDefault(r=> r.name == arg_name);

Comments

0

The LINQ solution, although compact and elegant, is inefficient. You could use a dictionary, mapping from name, to index inside the list. Take into account that this solution is inefficient in adding/removing items, especially if they're added/removed from the middle of that list.... Think about which solution is more appropriate for you

Comments

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.