IsSubclassOfRawGeneric

Is essentially a modified version of Type.IsSubClassOf that supports checking whether a class derives from a generic base-class without specifying the type parameters. For instance, it supports typeof(List<>) to see if a class derives from the List class. The actual code was borrowed from http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class.

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/// <summary>
/// Alternative version of <see cref="Type.IsSubclassOf"/> that supports raw generic types (generic types without
/// any type parameters).
/// </summary>
/// <param name="baseType">The base type class for which the check is made.</param>
/// <param name="toCheck">To type to determine for whether it derives from <paramref name="baseType"/>.</param>
public static bool IsSubclassOfRawGeneric(this Type toCheck, Type baseType)
{
while (toCheck != typeof(object))
{
Type cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (baseType == cur)
{
return true;
}

toCheck = toCheck.BaseType;
}

return false;
}

IsNotNullOrEmpty

It returns false if given collection is null or empty otherwise it returns true.

源代码:

1
2
3
4
public static bool IsNotNullOrEmpty(this System.Collections.Generic.IEnumerable<T> source)
{
return source != null && source.Any();
}

timeToDecimal

Convert string time(hh:mm) in decimal

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static Decimal timeToDecimal(this string time)
{
int Hours = time.Split(':')[0].ToInt();
decimal Minutes = time.Split(':')[1].ToInt();
while (Minutes >= 60)
{
Minutes = Minutes % 60;
Hours ++;
}
//Minutes = Minutes/60;
long test = Convert.ToInt64((Minutes/60)/10);
return Hours + Minutes/60;
}

ToObservableCollection<T>()

Convert a IEnumerable to a ObservableCollection and can be used in XAML (Silverlight and WPF) projects

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace Databinding01 {
public static class CollectionExtensions {

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll) {
var c = new ObservableCollection<T>();
foreach (var e in coll)
c.Add(e);
return c;
}
}
}

StringToTimeSpan

Converts a string to a timespan

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
/// <summary>
/// Converts a string time to a timespan.
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// A timespan object.
/// </returns>
public static TimeSpan StringToTimeSpan(this string time)
{
TimeSpan timespan;
var result = TimeSpan.TryParse(time, out timespan);
return result ? timespan : new TimeSpan(0, 0, 0);
}

ToDictionary() - for Enumerations of Groupings

Converts an IEnumerable<IGrouping<TKey,TValue>> to a Dictionary<TKey,List> so that you can easily convert the results of a GroupBy clause to a Dictionary of Groupings.

The out-of-the-box ToDictionary() LINQ extension methods require a key and element extractor which are largely redundant when being applied to an enumeration of groupings, so this is a short-cut.

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Collections.Generic;
using System.Linq;

namespace SharedAssemblies.Core.Extensions
{
// This class contains helper additions to linq.
public static class EnumerableExtensions
{
/// <summary>
/// Converts an enumeration of groupings into a Dictionary of those groupings.
/// </summary>
/// <typeparam name="TKey">Key type of the grouping and dictionary.</typeparam>
/// <typeparam name="TValue">Element type of the grouping and dictionary list.</typeparam>
/// <param name="groupings">The enumeration of groupings from a GroupBy() clause.</param>
/// <returns>A dictionary of groupings such that the key of the dictionary is TKey type and the value is List of TValue type.</returns>
public static Dictionary<TKey, List<TValue>> ToDictionary<TKey,TValue>(this IEnumerable<IGrouping<TKey,TValue>> groupings)
{
return groupings.ToDictionary(group => group.Key, group => group.ToList());
}
}
}

ToPagedList

Paging extension method for NHibernate 3.0 and its new query API QueryOver.

源代码:

1
2
3
4
5
6
7
8
9
10
public static class QueryOverExtensions
public static PagedList<T> ToPagedList<T>(this IQueryOver<T, T> queryOver, int pageIndex, int pageSize)
{
var rowCountQuery = queryOver.ToRowCountQuery();
IEnumerable<T> list = queryOver.Take(pageSize).Skip((pageIndex - 1) * pageSize).Future();
int totalCount = rowCountQuery.FutureValue<int>().Value;

return new PagedList<T>(list, pageIndex, pageSize, totalCount);
}
}

WhereIf

When building a LINQ query, you may need to involve optional filtering criteria. Avoids if statements when building predicates & lambdas for a query. Useful when you don’t know at compile time whether a filter should apply.

Borrowed from Andrew Robinson.
http://bit.ly/1V36G9

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}

public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, int, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}

通过IQueryable创建List泛型集合的异步方法

通过System.Collections.Generic.IQueryable创建System.Collections.Generic.List集合的异步方法

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ReflectionIT.Linq {

static class Utils {

/// <summary>
/// 通过System.Collections.Generic.IQueryable<T>.创建System.Collections.Generic.List<T>的异步方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static Task<List<T>> ToListAsync<T>(this IQueryable<T> list) {
return Task.Run(() => list.ToList());
}

}
}

C#扩展方法:获取枚举Enum的description内容

通过枚举的名称获取分配的Description内容

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

public static class EnumHelper<T>
{
public static string GetEnumDescription(string value)
{
Type type = typeof(T);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
}

示例

1
2
3
4
5
6
7
8
9
10
11
public enum GradeEnum
{
[Description("Passed")]
Pass,
[Description("Failed")]
Failed,
[Description("Promoted")]
Promoted
}

string description = EnumHelper<GradeEnum>.GetEnumDescription("pass");
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×