D.moon
D.moon

Reputation: 5

how to check if a target string is in the List<T> C#

I was thinking about finding a solution for this problem, The question said; ask the user to enter the target ssn (of type string) then search the collection of members, in case the ssn is found returns its index, other return-1, this should be done by defining and using a Generic method which takes List and string target as parameters,

My problem is that I can't correctly implements this method, I use CompareTo method to compare between the target and the List elements but this compression seems not logical since the target is string and the List elements are objects, This is my code

        public static int Search<T>(List<T> a, string target) where T : IComparable
    {
        int index = 0;
        for (int i = 1; i < a.Count(); i++)
        {
            if (target.CompareTo(a[i].ToString()) == 0)
                index = i;
            return i;
        }                

        return -1;

    }

Hepl me please to figure out a solution for this method, Thank you :)

Upvotes: 0

Views: 117

Answers (2)

Marcin Zdunek
Marcin Zdunek

Reputation: 1011

Why not to use FindIndex built-in method?

List<string> list = new List<string>();
list.Add("some");
list.Add("test");
int index = list.FindIndex(t => t.Equals("test"));

FindIndex returns -1 when not found

Upvotes: 0

usr
usr

Reputation: 171178

Since T is IComparable you could do:

a[i].CompareTo(target)

The compare method must be able to correctly deal with string inputs.

Frankly, I think the problem statement seems weird. This is not how it should be done.

You also could make the entire method generic:

public static int Search<T>(List<T> a, T target) where T : IComparable<T>
{
    for (int i = 0; i < a.Count; i++)
    {
        if (target.CompareTo(a[i]) == 0)
            return i;
    }
    return -1;
}

I've fixed the code, too...

Upvotes: 1

Related Questions