Monday, March 18, 2019

Get dictionary object from list


When you get dictionary object from a list in C#, make sure that you select distinct values for the dictionary key. Otherwise the compiler will throw run time error if there are duplicates.

lst.GroupBy(x=>x.id).Select(x=>x.First()).ToDictionary(r => r.id, k => k.enabled);

Here is an example of how to select distinct keys from list and to return them in dictionary object.


Tuesday, March 12, 2019

Lazy initialization in C#

Lazy<T> can be used in C# to delay the initialization of an object. It can be used in singleton architecture as given in the below example.

public static Lazy<MyClass> MyClassInstance = new Lazy<MyClass>(()=> new MyClass());