https://gist.github.com/jarrettmeyer/7539291
Category Archives: C#
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;
}
}
Calmsen статьи и примеры
Полезные статьи и примеры для шарпа
http://calmsen.ru/
Транслитерация Unidecode
http://unidecode.codeplex.com/
Библиотека для транслитерации на C# UnidecodeSharpFork
https://bitbucket.org/DimaStefantsov/unidecodesharpfork
По совету отсюда http://stackoverflow.com/questions/1841874/how-to-transliterate-cyrillic-to-latin-text
Условная валидация
Пример валидации значений одних полей в зависимости от других.
Отсюда: https://gist.github.com/elizabeth-young/5875161
Continue Reading →
PagedList
https://github.com/TroyGoode/PagedList
What is this?
PagedList is a library that enables you to easily take an IEnumerable/IQueryable, chop it up into «pages», and grab a specific «page» by an index. PagedList.Mvc allows you to take that «page» and display a pager control that has links like «Previous», «Next», etc.