2016-05-25 76 views
0

我想过滤包含复杂对象的DataTable或DaatView。在DataTable/DataView中过滤复杂对象

比方说,我有这样的对象者

public class Person{  

public int Id{get; set;}  
public int Age{get; set;}  
public strng Name{get; set;}  
public Address BillAddress{get; set;} 
} 

public class Address{   
public string 
Town{get; set}  
public string Street{get; set}  
public int Number{get; set} 
} 

现在我填一个DataView与Person对象的列表:

public static DataView ToObjectDataView<T>(this IList<T> list, int countOfColumns) 
    { 
    if (list == null || countOfColumns < 1) 
    { 
     return null; 
    } 
    int columns = countOfColumns; 

    DataTable dataTable = new DataTable(); 

    for (int currentCol = 0; currentCol != columns; currentCol++) 
    { 
     DataColumn column = new DataColumn(currentCol.ToString(), typeof(T)); 
     dataTable.Columns.Add(column); 
    } 

    DataRow row = null; 
    int currentColumn = 0; 
    for (int index = 0; index < list.Count; index++) 
    { 
     if (list[index] == null) 
     { 
      continue; 
     } 
     if (Equals(null, row)) 
      row = dataTable.NewRow(); 

     row[currentColumn] = list[index]; 
     currentColumn++; 

     if (currentColumn == columns) 
     { 
      dataTable.Rows.Add(row); 
      row = null; 
      currentColumn = 0; 
     } 
    } 

    //Verarbeitung der letzten Zeile 
    if (!Equals(null, row)) 
    { 
     dataTable.Rows.Add(row); 
    } 

    return new DataView(dataTable); 
    } 

让我与Person对象的10列的数据视图, evrey专栏有它的索引名称:

IList<Person> personList = new List<Person>(); 
// Fill the list... 
DataView dataSource = personList.ToObjectDataSource(10); 

现在我想过滤这个DataVi例如,根据孩子的价值观和表达方式,让所有居住在'假客户'的人都能获得。

我试过“0.BillAddress.Street =‘Fakestreet’”(和或与其他列表达),但不工作..

回答

0

这是一个部分解决方案,因为我没有找到直接的方式。

使用的DataTable AsEnumerable延伸和动态LINQ过滤器(System.Linq.Dynamic(也可为.NET 3.5))

// Filter directly the List 
    public static List<T> FilterByLinqExpression<T>(this IList<T> list, string linqFilterExpression) 
    { 
    var result = list.AsQueryable().Where(linqFilterExpression); 
    return result.ToList<T>(); 
    } 

所以,你可以这样调用它对于生活在一个所有人街头有“大道”在它的名字:

IList<Person> personList = new List<Person>(); 
// Fill the list... 
var filteredValues = personList.FilterByLinqExpression("((BillAddress.Street).Contains(\"Avenue\"))"); 
DataView dataSource = filteredValues .ToObjectDataSource(10); 

我使用它来过滤出用于显示在DevExpress的ASPxGridView例如复杂的对象。顺便说一下,他们有一个从他们的过滤器表达式到不同的过滤器表达式的自动转换器,在我的情况下,'CriteriaToWhereClauseHelper.GetDynamicLinqWhere()'将给定的过滤器表达式转换为动态的linq表达式。