簡體   English   中英

過濾DataTable / DataView中的復雜對象

[英]Filter complex objects in DataTable/DataView

我想過濾包含復雜對象的DataTable或DaatView。

假設我有這個對象

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} 
}

現在,我用一個Person對象列表填充一個DataView:

  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);
  }

為了使我得到一個具有10列Person對象的DataView,evrey列具有其索引的名稱:

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

現在,我想基於帶有子表達式的子值來過濾此DataView,例如,獲取所有居住在“假街”中的人。

我嘗試了“ 0.BillAddress.Street ='Fakestreet'”(和或帶有其余列的表達式),但這不起作用。

這是部分解決方案,因為我沒有找到直接的方法。

將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表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM