sh3rifme
sh3rifme

Reputation: 1064

Return object from list of objects based on variable in C#

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?

Upvotes: 3

Views: 3006

Answers (3)

Shlomi Borovitz
Shlomi Borovitz

Reputation: 1700

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

Upvotes: 0

Matan Shahar
Matan Shahar

Reputation: 3240

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);

Upvotes: 0

Habib
Habib

Reputation: 223207

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)

Upvotes: 8

Related Questions