The code below is part of authorization. I am trying to mentally imaging what it actually does but could not somehow.
IsAuthorized = ((x, y) => x.Any(z => y.Contains(z)));
Could anyone explain this lambda expression to me?
Thanks!
Edit:
IsAuthorized is a delegate type. The previous programmer who code this seems want to keep it secret by putting delegate to the end of cs file.
The actual code is:
public delegate bool IsAuthorized(IEnumerable<Int32> required, IEnumerable<Int32> has);
IsAuthorized = ((x, y) => x.Any(z => y.Contains(z)));
Sure - it's saying given a pair (x, y)
, does x
contain any values such that y
contains that value.
Looks to me like it's really saying "is there any intersection between x
and y
".
So an alternative would probably be:
IsAuthorized = (x, y) => x.Intersect(y).Any();
It's just possible that that wouldn't work, depending on the type of IsAuthorized
, but I expect it to be correct.
To go with Jon's explanation, here is (hopefully) an equivalent sample with outputs:
static void Main(string[] args)
{
int[] i = new int[] { 1, 2, 3, 4, 5 };
int[] j = new int[] { 5, 6, 7, 8, 9 };
int[] k = new int[] { 0, 6, 7, 8, 9 };
bool jContainsI = i.Any(iElement => j.Contains(iElement));
bool kContainsI = i.Any(iElement => k.Contains(iElement));
Console.WriteLine(jContainsI); // true
Console.WriteLine(kContainsI); // false
Console.Read();
}
Basically, is any element of i
in j
or k
. This assumes that your x
and y
parameters are collections of some variety.
Intersection is a valid alternative here:
bool iIntersectsJ = i.Intersect(j).Any(); // true
bool iIntersectsK = i.Intersect(k).Any(); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With