[英]Sort a List<T> into List<List<T>> based on type using Linq?
[英]Sort List<T> using string without Linq
有沒有辦法使用類似"Name desc"
(與DataTable.DefaultView.Sort
相同)而不是 Linq 之類的字符串對List<T>
進行排序?
我正在嘗試用Lists
替換DataTables
,我需要它來做到這一點以與舊代碼兼容。
解決方案
使用 V4Vendetta 的代碼我能夠創建這個擴展方法,測試似乎表明它有效。
public static void SortByString<T>(this List<T> list, string sortString)
{
if (sortString == null) return;
List<string> SortGroups = sortString.Split(',').ToList();
for (int i = SortGroups.Count - 1; i >= 0; i--)// sort from the last group first
{
string tempColumn = SortGroups[i].Trim().Split(' ')[0];
bool isAsc = SortGroups[i].Trim().Split(' ').Length > 1 ? SortGroups[i].Trim().Split(' ')[1].ToLower() == "asc" ? true : false : true;
PropertyInfo propInfo = typeof(T).GetProperty(tempColumn);
if (propInfo == null) // if null check to make sure its not just a casing issue.
{
foreach (PropertyInfo pi in typeof(T).GetProperties())
{
if(pi.Name.ToLower() == tempColumn.ToLower())
{
tempColumn = pi.Name;
propInfo = typeof(T).GetProperty(tempColumn);
break;
}
}
}
if (propInfo != null)
{
Comparison<T> compare = delegate(T a, T b)
{
object valueA = isAsc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);
object valueB = isAsc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);
return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;
};
list.Sort(compare);
}else{
throw new IndexOutOfRangeException("Property: '" + tempColumn + "', does not exist in '" + typeof(T).ToString() + "'");
}
}
}
List有一些排序方法,有些采用您可以實現的Comparison<T>
進行自定義比較排序
據我所知,這種類型的搜索沒有內置支持。 所以你必須自己寫。
解析字符串應該不會太難。 以逗號 (,) 將其拆分,以防您有類似“name asc, age desc”之類的排序字符串,並將每個字符串視為名稱和方向。 然后,您可以對類型 T 使用反射來查找要排序的屬性並構建一個執行所需比較的方法。
以 codeplex 上的這篇文章為例: http://www.codeproject.com/KB/linq/dynamite_dynamic_sorting.aspx
我在這些線路上嘗試過一些東西,也許你需要即興發揮它來滿足你的需要
private List<Employee> CreateSortList<T>(
IEnumerable<Employee> dataSource,
string fieldName, SortDirection sortDirection)
{
List<Employee> returnList = new List<Employee>();
returnList.AddRange(dataSource);
// get property from field name passed
System.Reflection.PropertyInfo propInfo = typeof(T).GetProperty(fieldName);
Comparison<Employee> compare = delegate(Employee a, Employee b)
{
bool asc = sortDirection == SortDirection.Ascending;
object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);
object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);
//comparing the items
return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;
};
returnList.Sort(compare);
return returnList;
}
您需要傳遞適當的排序方向和字段名,這將是 class 的屬性(在我的情況下是員工)
希望這可以幫助
查看專門的 collections 命名空間。 那里應該有一個排序列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.