Gets the Description attribute from an Enum

public static class EnumEx
    public static T GetValueFromDescription<T>(string description)
        var type = typeof(T);
        if(!type.IsEnum) throw new InvalidOperationException();
        foreach(var field in type.GetFields())
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if(attribute != null)
                if(attribute.Description == description)
                    return (T)field.GetValue(null);
                if(field.Name == description)
                    return (T)field.GetValue(null);
        throw new ArgumentException("Not found.", "description");
        // or return default(T);


var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");

source: stackoverflow


c# Anonymous Recursion

Break it down into two statements and use the magic of captured variables to achieve the recursion effect:

private delegate string myDelegate(Object bj);
myDelegate build = null;
build = delegate(Object bj)
           var letters= string.Empty;
           if (someCondition)
               return build(some_obj);                            
           else string.Empty;
 source: anonymous-recursion-in-c

Func vs. Action vs. Predicate Delegates

  • Predicate: essentially Func<T, bool>; asks the question “does the specified argument satisfy the condition represented by the delegate?” Used in things like List.FindAll.
  • Action: Perform an action given the arguments. Very general purpose. Not used much in LINQ as it implies side-effects, basically.
  • Func: Used extensively in LINQ, usually to transform the argument, e.g. by projecting a complex structure to one property.

Other important delegates:

  • EventHandler/EventHandler<T>: Used all over WinForms
  • Comparison<T>: Like IComparer<T> but in delegate form.


The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ – for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we’d already had Func and Action in their various guises, Predicate wouldn’t have been introduced… although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.


source: stackoverflow

C# LINQ find duplicates in List

The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In linq, this translates to:

var query = lst.GroupBy(x=>x)

If you want to know how many times the elements are repeated, you can use:

var query = lst.GroupBy(x=>x)
              .Select(y=> new { Element = y.Key, Counter = y.Count()})

This will return a List of an anonymous type, and each element will have the properties Element and Counter, to retrieve the informations you need.

And lastly, if it’s a dictionary you are looking for, you can use

var query = lst.GroupBy(x=>x)

This will return a dictionary, with your element as key, and the number of times it’s repeated as value.



RegisterType with a PARAMETER constructor

class ThreadPool
   public ThreadPool(int maxThreads, ILogger logger)
container.RegisterType<ThreadPool>(new InjectionConstructor(20,typeof(ILogger)));

I suppose using typeof in this scenario makes some sense, but it’s hardly intuitive.  The API could be improved so that I don’t need to specify anything about ILogger resolution at all.   I should only have to specify explicitly the constructor arguments that cannot be resolved automatically, e.g.:

container.RegisterType<ThreadPool>().WithConstructorArg("maxThreads", 20);


Using LINQ to remove elements from a List

Well, it would be easier to exclude them in the first place:

authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();

However, that would just change the value of authorsList instead of removing the authors from the previous collection. Alternatively, you can use RemoveAll:

authorsList.RemoveAll(x => x.FirstName == "Bob");

If you really need to do it based on another collection, I’d use a HashSet, RemoveAll and Contains:

var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));

How to convert DataTable to class Object

Initialize DataTable:

DataTable dt = new DataTable(); 
dt.Columns.Add("id", typeof(String)); 
dt.Columns.Add("name", typeof(String)); 
for (int i = 0; i < 5; i++)
    string index = i.ToString();
    dt.Rows.Add(new object[] { index, "name" + index });

Query itself:

IList<Class1> items = dt.AsEnumerable().Select(row => 
    new Class1
            id = row.Field<string>("id"),
            name = row.Field<string>("name")