public
static
class
IEnumerableExtensions
{
public
static
IOrderedEnumerable<T> OrderBy<T>(
this
IEnumerable<T> list,
string
sortExpression)
{
sortExpression +=
""
;
string
[] parts = sortExpression.Split(
' '
);
bool
descending =
false
;
string
property =
""
;
if
(!(parts.Length > 0 && parts[0] !=
""
))
{
throw
new
Exception(
"Invalid sort expression."
);
}
property = parts[0];
if
(parts.Length > 1)
{
descending = parts[1].ToLower().Contains(
"esc"
);
}
PropertyInfo prop =
typeof
(T).GetProperty(property);
if
(prop ==
null
)
{
throw
new
Exception(
"No property '"
+ property +
"' in + "
+
typeof
(T).Name +
"'"
);
}
if
(descending)
return
list.OrderByDescending(x => prop.GetValue(x,
null
));
else
return
list.OrderBy(x => prop.GetValue(x,
null
));
}
public
static
IOrderedEnumerable<T> ThenBy<T>(
this
IOrderedEnumerable<T> list,
string
sortExpression)
{
sortExpression +=
""
;
string
[] parts = sortExpression.Split(
' '
);
bool
descending =
false
;
string
property =
""
;
if
(!(parts.Length > 0 && parts[0] !=
""
))
{
throw
new
Exception(
"Invalid sort expression."
);
}
property = parts[0];
if
(parts.Length > 1)
{
descending = parts[1].ToLower().Contains(
"esc"
);
}
PropertyInfo prop =
typeof
(T).GetProperty(property);
if
(prop ==
null
)
{
throw
new
Exception(
"No property '"
+ property +
"' in + "
+
typeof
(T).Name +
"'"
);
}
if
(descending)
return
list.ThenByDescending(x => prop.GetValue(x,
null
));
else
return
list.ThenBy(x => prop.GetValue(x,
null
));
}
public
static
IEnumerable<T> OrderByStringExpression<T>(
this
IEnumerable<T> queryObj,
string
orderByProperties)
{
if
(
string
.IsNullOrWhiteSpace(orderByProperties))
{
return
queryObj;
}
string
[] orderByPropertyArray = orderByProperties.Split(
new
char
[] {
','
}, StringSplitOptions.RemoveEmptyEntries);
IOrderedEnumerable<T> orderedItem =
null
;
if
(orderByPropertyArray.Length > 0)
{
orderedItem = queryObj.OrderBy(orderByPropertyArray[0]);
if
(orderByPropertyArray.Length > 1)
{
for
(
int
i = 1; i < orderByPropertyArray.Length; i++)
{
orderedItem = orderedItem.ThenBy(orderByPropertyArray[i]);
}
}
}
return
orderedItem;
}
}