LeetCode: Intersection of two arrays ii C# https://leetcode.com/problems/intersection-of-two-arrays-ii/

Please review for performance, I am having a problem with using TryGetValue, if someone can explain how this can be used in here.


  Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:

  
  Each element in the result should appear as many times as it shows in
  both arrays. The result can be in any order.


using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// &lt;summary&gt;
    /// https://leetcode.com/problems/intersection-of-two-arrays-ii/
    /// &lt;/summary&gt;
    [TestClass]
    public class IntersectionOfTwoArraysii
    {
        [TestMethod]
        public void IntersectionOfDouble2Test()
        {
            int[] nums1 = {1, 2, 2, 1};
            int[] nums2 = {2, 2};
            CollectionAssert.AreEqual(nums2, Intersect(nums1,nums2));
        }

        public int[] Intersect(int[] nums1, int[] nums2)
        {
            if (nums1.Length &gt; nums2.Length)
            {
                return Intersect(nums2, nums1);
            }
            Dictionary&lt;int, int&gt; nums1Count = new Dictionary&lt;int, int&gt;();
            List&lt;int&gt; res = new List&lt;int&gt;();
            foreach (var num in nums1)
            {
                if (!nums1Count.ContainsKey(num))
                {
                    nums1Count.Add(num,1);
                }
                else
                {
                    nums1Count[num]++;
                }
            }

            foreach (var num in nums2)
            {
                if (nums1Count.ContainsKey(num) &amp;&amp; nums1Count[num] &gt; 0)
                {
                    res.Add(num);
                    nums1Count[num]--;
                }
            }

            return res.ToArray();
        }
    }
}
if (!nums1Count.ContainsKey(num))
            {
                nums1Count.Add(num,1);
            }
            else
            {
                nums1Count[num]++;
            }



I think it can be written as:

nums1Count.TryGetValue(num, out int count);
nums1Count[num] = count + 1;


You don't have to test the return value of TryGetValue() in this case, because TryGetValue() sets count to default (0) if it returns false.

The loop could also be written as a LINQ sequence as:

var nums1Count = data.GroupBy(i =&gt; i).ToDictionary(gr =&gt; gr.Key, gr =&gt; gr.Count());




Likewise:


            if (nums1Count.ContainsKey(num) &amp;&amp; nums1Count[num] &gt; 0)
            {
                res.Add(num);
                nums1Count[num]--;
            }



can be changed to:

if (nums1Count.TryGetValue(num, out int count) &amp;&amp; count &gt; 0)
{
  res.Add(num);
  nums1Count[num]--;
}