Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could anyone explain this lambda expression to me? It's kind getting me crazy

Tags:

c#

.net

lambda

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)));
like image 356
wei Avatar asked Sep 01 '11 15:09

wei


Video Answer


2 Answers

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.

like image 126
Jon Skeet Avatar answered Sep 21 '22 04:09

Jon Skeet


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
like image 40
Adam Houldsworth Avatar answered Sep 20 '22 04:09

Adam Houldsworth