none
Code regarding Updating items of one List<t> that match another List<t> RRS feed

  • Question

  • i got a code from here https://codereview.stackexchange.com/a/11021/197025

    which is not very clear. please tell me what lookup function is doing?

    List<ExampleT> a, List<ExampleT> b

    var aLookup = a.ToLookup(x => new { x.MatchA, x.MatchB }); foreach (var bItem in b) { foreach (var aItem in aLookup[new { bItem.MatchA, bItem.MatchB }]) aItem.ToUpdate = bItem.ToUpdate; }

    this line is not clear please explain var aLookup = a.ToLookup(x => new { x.MatchA, x.MatchB });

    and also this line is not clear var aItem in aLookup[new { bItem.MatchA, bItem.MatchB }]

    please explain


    • Edited by Sudip_inn Sunday, April 7, 2019 11:35 AM
    Sunday, April 7, 2019 11:34 AM

Answers

  • Inside the parentheses is a "lambda function", which is a nameless function.  It accepts one parameter, and returns a list containing two items.  The ToLookup function will take each item from the List a, pass that item to the function, and use the results to build a "Lookup" object.  A Lookup object is very similar to a Dictionary, in that stores a set of items index by key.  In this case, MatchA will be the key, and MatchB will be the value.

    So, "aLookup" will be of type Lookup<ExampleT,ExampleT>.

    Then, the loop goes through each element in the "b" list.  For each item, it tries to find the item from aLookup with the same MatchA value.  For each match, it updates the "aLookup" item with the value from the "b" list.

    So, this is basically merging the two lists.  aLookup will contain all of the "a" items, but any items that are also in "b" will be updated with the "b" value.

    https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tolookup?view=netframework-4.7.2


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    • Marked as answer by Sudip_inn Monday, April 8, 2019 7:30 PM
    Monday, April 8, 2019 6:19 AM