简体   繁体   中英

c# Writing an extension method to extend functionality in System.Linq

I have only used extension methods a few times in the past so excuses me if this is a really stupid question.

I have a 3 different arrays of strings, I also have 3 strings that I want to search for within these arrays.

So far I have something like this:

if (list1.Any(x => x == term1) && list2.Any(x => x == term2) && list3.Any(x => x == term3))
            {
                //do something
            }

So if all terms are found the if statement should = true.

The problem I'm trying to solve with a extention method is....

There is a possibility term1, term2, term3 could have a value of "-1" if this is the case I want to ignore it in the if statement.

So my question is, can this be done with an extension method? So instead of using list.Any() I can use list.MyMethod() that will return true if the value of any of the terms is -1.

Sure, you can use an extension method. Whether you should is a different question entirely.

public static class MyExtensions
{
    public static bool MyMethod<T>(this IEnumerable<T> list, T term)
    {
        if(term != null && term.ToString() == "-1")
          return false; // or true, whichever is your requirement.
        return list.Any(x => x == term);
    }
}

usage

if(list1.MyMethod(term1) && list2.MyMethod(term2) && list3.MyMethod(term3)) { ... }

nb. Don't call it MyMethod whatever you do!

You could define a fairly simple method to do this. I'll assume strings, but making this use generics is not too much harder (just gets into weird logic with figuring out what -1 is generically):

static class MyExtensions 
{
     public static bool AnyOrMinusOne(this IEnumerable<string> list, string term) 
     {
        return term == "-1" || list.Any(x => x == term);
     }
}

Then your statement becomes:

if (list1.AnyOrMinusOne(term1) && list2.AnyOrMinusOne(term2) && list3.AnyOrMinusOne(term3))
{
    //do something
}

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