简体   繁体   中英

C# locate and return string in List<t>

I have a List<Borrower> called BorrowerList. I want to be able to find and return a string value ( name ) from the list. The solution from a similar question does not work for me (uses Linq)

public Borrower FindBorrower(string name)
{
     var match = BorrowerList.FirstOrDefault(stringToCheck => stringToCheck.Contains(name));
     // error raised here says: does not contain a definition for 'Contains' and the best extension method overload
     return match;
}

If it helps this is the code for Borrower

class Borrower
{
    private string name;
    private Book b;

    public Borrower(string n)
    {
        name = n;
    }

    public string GetName()
    {
        return name;
    }

    public Book GetBook()
    {
        return b;
    }

    public void SetBook(Book b)
    {
        this.b = b;
    }
}

The error comes from your Borrower class, it does not have a Contains method.

It appears that you have unsuccessfully transposed a solution that would work for a List<string> to your List<Borrower> .

The simplest fix is:

var match = BorrowerList.FirstOrDefault(borrower => borrower.Name.Contains(name));

This assumes you add a string Name {get;} property to Borrower . If not, then...

var match = BorrowerList.FirstOrDefault(borrower => borrower.GetName().Contains(name));

...should suffice.


By way of an explanation, the signature FirstOrDefault is a Func<T, bool> . In this case T is Borrower , not string , so you need drill into the properties / methods of Borrower to get the name.

There are, perhaps, nicer solutions to this problem. For the time being though, this should get you past the issue.

If i guess right that was your intention:

    public Borrower FindBorrower(string name)
    {
        var match = BorrowerList.Where(x => x.nameToCheck.Contains(name)).FirstOrDefault();
        return match;
    }

}

class Borrower
{
    public string nameToCheck { get; set; }
    // the rest of class definitions...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM