Работа с полями класса

http://stackoverflow.com/questions/9210428/how-to-convert-class-into-dictionarystring-string

someObject.GetType()
     .GetProperties(BindingFlags.Instance | BindingFlags.Public)
          .ToDictionary(prop => prop.Name, prop => prop.GetValue(someObject, null))

http://stackoverflow.com/questions/4943817/mapping-object-to-dictionary-and-vice-versa/4944547#4944547

public static class ObjectExtensions
{
    public static T ToObject(this IDictionary source)
        where T : class, new()
    {
            T someObject = new T();
            Type someObjectType = someObject.GetType();

            foreach (KeyValuePair item in source)
            {
                someObjectType.GetProperty(item.Key).SetValue(someObject, item.Value, null);
            }

            return someObject;
    }

    public static IDictionary AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    {
        return source.GetType().GetProperties(bindingAttr).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source, null)
        );

    }
}

class A
{
    public string Prop1
    {
        get;
        set;
    }

    public int Prop2
    {
        get;
        set;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary dictionary = new Dictionary();
        dictionary.Add("Prop1", "hello world!");
        dictionary.Add("Prop2", 3893);
        A someObject = dictionary.ToObject();

        IDictionary objectBackToDictionary = someObject.AsDictionary();
    }
}

http://stackoverflow.com/questions/2051834/exclude-property-from-gettype-getproperties

public class SkipPropertyAttribute : Attribute
{
}

public static class TypeExtensions
{
    public static PropertyInfo[] GetFilteredProperties(this Type type)
    {
        return type.GetProperties().Where(pi => pi.GetCustomAttributes(typeof(SkipPropertyAttribute), true).Length == 0).ToArray();
    }       
}

public class Test
{
    public string One { get; set; }

    [SkipProperty]
    public string Two { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var t = new Test();
        Type ty = t.GetType();

        PropertyInfo[] pinfo = ty.GetFilteredProperties();
        foreach (PropertyInfo p in pinfo)
        {
            Console.WriteLine(p.Name);
        }

        Console.ReadKey();
    }
}

http://stackoverflow.com/questions/4951233/compare-two-objects-and-find-the-differences

static class extentions
{
    public static List DetailedCompare(this T val1, T val2)
    {
        List variances = new List();
        FieldInfo[] fi = val1.GetType().GetFields();
        foreach (FieldInfo f in fi)
        {
            Variance v = new Variance();
            v.Prop = f.Name;
            v.valA = f.GetValue(val1);
            v.valB = f.GetValue(val2);
            if (!v.valA.Equals(v.valB))
                variances.Add(v);

        }
        return variances;
    }


}
class Variance
{
    public string Prop { get; set; }
    public object valA { get; set; }
    public object valB { get; set; }
}

LINQ Join vs. Contains

Хозяйке на заметку.
В данном примере всё выполняется в памяти приложения.

http://stackoverflow.com/questions/16824510/select-multiple-records-based-on-list-of-ids-with-linq

Solution with .Where and .Contains has complexity of O(N square). Simple .Join should have a lot better performance (close to O(N) due to hashing). So the correct code is:

_dataContext.UserProfile.Join(idList, up => up.ID, id => id, (up, id) => up);

And now result of my measurement. I generated 100 000 UserProfiles and 100 000 ids. Join took 32ms and .Where with .Contains took 2 minutes and 19 seconds! I used pure IEnumerable for this testing to prove my statement. If you use List instead of IEnumerable, .Where and .Contains will be faster. Anyway the difference is significant. The fastest .Where .Contains is with Set. All it depends on complexity of underlying coletions for .Contains. Look at this post to learn about linq complexity.Look at my test sample below:

    private static void Main(string[] args)
    {
        var userProfiles = GenerateUserProfiles();
        var idList = GenerateIds();
        var stopWatch = new Stopwatch();
        stopWatch.Start();
        userProfiles.Join(idList, up => up.ID, id => id, (up, id) => up).ToArray();
        Console.WriteLine("Elapsed .Join time: {0}", stopWatch.Elapsed);
        stopWatch.Restart();
        userProfiles.Where(up => idList.Contains(up.ID)).ToArray();
        Console.WriteLine("Elapsed .Where .Contains time: {0}", stopWatch.Elapsed);
        Console.ReadLine();
    }

    private static IEnumerable GenerateIds()
    {
       // var result = new List();
        for (int i = 100000; i > 0; i--)
        {
            yield return i;
        }
    }

    private static IEnumerable GenerateUserProfiles()
    {
        for (int i = 0; i < 100000; i++)
        {
            yield return new UserProfile {ID = i};
        }
    }

Console output:

Elapsed .Join time: 00:00:00.0322546
Elapsed .Where .Contains time: 00:02:19.4072107

А вот про SQL

http://stackoverflow.com/questions/1200295/sql-join-vs-in-performance

If the joining column is UNIQUE and marked as such, both these queries yield the same plan in SQL Server.

If it’s not, then IN is faster than JOIN on DISTINCT.

Enum to Dictionary с локализацией

Пример про локализацию
http://adamyan.blogspot.com/2010/02/aspnet-mvc-2-localization-complete.html

Пример с приведением enum к dictionary без лишних заморочек
http://stackoverflow.com/questions/5583717/enum-to-dictionary-c-sharp

var dict = Enum.GetValues(typeof(typFoo))
               .Cast()
               .ToDictionary(t => (int)t, t => t.ToString() );

Пример с generic-методом для enum
http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum

public T GetEnumFromString(string value) where T : struct, IConvertible
{
   if (!typeof(T).IsEnum) 
   {
      throw new ArgumentException("T must be an enumerated type");
   }

   //...
}
public abstract class EnumClassUtils
where TClass : class
{

    public static TEnum Parse(string value)
    where TEnum : struct, TClass
    {
        return (TEnum) Enum.Parse(typeof(TEnum), value);
    }

}

public class EnumUtils : EnumClassUtils
{
}

Наконец, собранное воедино — generic-метод, преобразующий enum к словарю на нужном языке. Может быть, надо доработать.

public static Dictionary TranslateEnum() where TEnum : struct, IConvertible
        {
            if (!typeof(TEnum).IsEnum)
            {
                throw new ArgumentException("TEnum must be an enumerated type");
            }

            var lang = typeof(MyLangStrings);

            var dict = Enum.GetValues(typeof(TEnum))
               .Cast()
               .ToDictionary(t => (int)Enum.Parse(typeof(TEnum), t.ToString()), t =>
               {
                   var p = lang.GetProperty(t.ToString());
                   return p.GetValue(p.DeclaringType, null).ToString();
               });
            return dict;
        }

Работа с параметрами запроса

Интересный пример
http://stackoverflow.com/questions/5818065/how-to-pass-request-querystring-to-url-action

public static RouteValueDictionary ToRouteValues(this NameValueCollection col, Object obj)
{
    var values = new RouteValueDictionary(obj);
    if (col != null)
    {
        foreach (string key in col)
        {
            //values passed in object override those already in collection
            if (!values.ContainsKey(key)) values[key] = col[key];
        }
    }
    return values;
}
Then you can use it like so:

Url.Action("action", "controller", Request.QueryString.ToRouteValues(new{ id=0 }));

Копирование объектов

https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx

public class Person 
{
    public int Age;
    public string Name;
    public IdInfo IdInfo;

    public Person ShallowCopy()
    {
       return (Person) this.MemberwiseClone();
    }

    public Person DeepCopy()
    {
       Person other = (Person) this.MemberwiseClone();
       other.IdInfo = new IdInfo(IdInfo.IdNumber);
       other.Name = String.Copy(Name);
       return other;
    }
}