简体   繁体   中英

c# - Using input parameter of lambda expression in if statement

I have if statement like this:

if (myList.Any(x => s.Contains(x))
{
//some code here
}

in which I check if there is a string in myList which is contained in a string s. Is it somehow possible to get the element x of this list and use it in the if statement showed above (in "//some code here" part), when the condition is met?

Thank you.

Switch from Any to FirstOrDefault , that will return the item that matched the test or null if no item was matched.

var found = myList.FirstOrDefault(x => s.Contains(x));
if (found != null)
{
//some code here
}

If null could be considered a "valid value" for a element in myList you can create a extension method TryFirst

public static class ExtensionMethods
{
    public static bool TryFirst<T>(this IEnumerable<T> @this, Func<T, bool> predicate, out T result)
    {
        foreach (var item in @this)
        {
            if (predicate(item))
            {
                result = item;
                return true;
            }
        }
        result = default(T);
        return false;
    }
}

This would let you do

string foundString;
var wasFound = myList.TryFirst(x => s.Contains(x), out foundString);
if (wasFound)
{
//some code here
}

and tell the difference between a null in your list and a default result.

The above two methods only act on the first item on the list that the Contains will match, if you want to act on all the items use a Where( clause and a foreach

foreach(var item in myList.Where(x => s.Contains(x))
{
//some code here
}

You must promise you will not use the following code and use one of the other options first

You can also do your stated question, it is possible to get a variable assigned to inside lambada. However this can not be done with expression lambadas, only with statement lambadas.

string matachedString = null;
if (myList.Any(x => { var found = s.Contains(x);
                      if(found)
                          matachedString = x;
                      return found;
                     });
{
//some code here
}

But only do this option as a last resort, use one of the more appropriate methods like FirstOrDefaut or write a custom method like TryFirst first.

I'd use foreach / Where() for this, even if I'm only expecting 0 or 1 result:

foreach (var item in myList.Where(x => s.Contains(x)))
{
    //some code here
}

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