C# has InList() function?

  • Thread starter Thread starter ABC
  • Start date Start date
ABC said:
Is there any function in C# to do as:

result true if InList('abc,ihjl,dkfd,ooo', 'abc');

Are you specifically wanting it for that usage? IList has the Contains
method, and Array (which implements IList explicitly) also has IndexOf.
So, you're fine if you've actually already got a list. You can get a
list from a string using string.Split, but for the example you gave it
might be simpler to use:

string x = "abc,ihjl,dkfd,ooo";
if (x.StartsWith("abc") || x.IndexOf(",abc") != -1)
{
...
}

Jon
 
ABC,

I just want to add that the you even don't need to declare a string variable
you can call the methods directly on the string constant like

bool f = "sdasdadasd".IndexOf("dad") != -1;

*f* will be *true* of the string contains the substring.
 
Jon Skeet said:
Are you specifically wanting it for that usage? IList has the Contains
method, and Array (which implements IList explicitly) also has IndexOf.
So, you're fine if you've actually already got a list. You can get a
list from a string using string.Split, but for the example you gave it
might be simpler to use:

string x = "abc,ihjl,dkfd,ooo";
if (x.StartsWith("abc") || x.IndexOf(",abc") != -1)
{
...
}

Will that fail if x = 'abcd,xxx,yyy,zzz' or x = 'xxx,abcd,yyy', etc? Or am I
just too tired to think of this properly at the moment?
 
Tim said:
Will that fail if x = 'abcd,xxx,yyy,zzz' or x = 'xxx,abcd,yyy', etc? Or am I
just too tired to think of this properly at the moment?

No, you're absolutely right. You potentially want:

if (x.StartsWith("abc,") ||
x.IndexOf(",abc,") != -1 ||
x.EndsWith(",abc") ||
x=="abc")

String.Split would still probably be less efficient, but would be
simpler at that stage :)

Good catch.

Jon
 
I know this is old, but I wanted the new readers to know that there is a new method to do this using generics and extension methods.

You can read my blog post to see more information about how to do this, but the main idea is this:

By adding this extension method to your code:

Code:
    public static bool IsIn<T>(this T source, params T[] values)
    {
        return values.Contains(source);
    }

you can perform your search like this:

Code:
    string myStr = "str3"; 
    bool found = myStr.IsIn("str1", "str2", "str3", "str4");

It works on any type (as long as you create a good equals method). Any value type for sure.
 
Back
Top