Should we initialize List(T) with size if known ?

As per documentation, it says

If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List.

We can decrease the capacity of a List(T) any time by calling TrimExcess method over the List(T).
If we decrease the capacity, interestingly, it is not decreased, but the memory is relocated and all the elements in the List(T) are copied into that memory location.

dafault capacity if not defined is “0”. A List doubles itself, every time the capacity limit is hit.

Capacity for the List could be checked easily, any time using List(T).Capacity property.

           List<string> animals = new List<string>();

            animals.Add("cow");
            animals.Add("bull");           

            // get List<string> capacity
            int listCapacity = animals.Capacity;
          
            // get List<string> size
            int listSize = animals.Count;

            // reduce capacity 
            animals.TrimExcess();

            // make Lis<string> empty
            animals.Clear(); 
Advertisements

Using LINQ with Generic Dictionary in C#

Here is quick example for how to manipulate a Dictionary object for some constraint and get a new Dictionary Object from that, using LINQ.

Suppose we have a Dictionary as follows, which hold some of the values which might be null

 Dictionary<string, string> dictionaryWithNullValues = new Dictionary<string, string>();

Adding Items to Dictionary

            dictionaryWithNullValues.Add("one", "one");
            dictionaryWithNullValues.Add("two", null);
            dictionaryWithNullValues.Add("three", "three");
            dictionaryWithNullValues.Add("four", "four");
            dictionaryWithNullValues.Add("five", null);

Problem: we need a new dictionary object, almost same as the old one, but without the null values, from the old dictionary. Here is how we do this, using my beloved LINQ

   dictionaryWithoutNullValues =
   dictionaryWithNullValues
   .Where(d => d.Value != null)
   .ToDictionary(s => s.Key, s => s.Value);

To check the difference between both Dictionary Objects and verify, if this has worked, call the following properties on both old and new Dictionary Objects

Console.WriteLine("OldDictionary Keys: " + dictionaryWithNullValues.Keys.Count);
Console.WriteLine("OldDictionary Values: " + dictionaryWithNullValues.Values.Count);

Console.WriteLine("NewDictionary Keys: " + dictionaryWithoutNullValues.Keys.Count);
Console.WriteLine("NewDictionary Values: " + dictionaryWithoutNullValues.Values.Count);