2016-09-13 2 views
0

아래의 유틸리티 기능 (데이터 테이블에 나열)에서 목록의 일부 멤버를 제외 할 수 있습니까?데이터 테이블을 만들기 위해 일부 목록 속성을 제외하는 방법

처럼, 나는 속성을 만들고, 아래의 유틸리티 메소드에

public class PointDataClone 
{ 
    public int DataId { get; set; } 
    public string UniqueKey { get; set; } 
    public int Count { get; set; } 
    public List<PointToPointData> PointToPointData { get; set; } 
} 

유틸리티 기능,

public static DataTable ToDataTable<T>(this List<T> iList) 
    { 
     DataTable dataTable = new DataTable(); 
     PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(typeof(T)); 
     for (int i = 0; i < propertyDescriptorCollection.Count; i++) 
     { 
      PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i]; 
      Type type = propertyDescriptor.PropertyType; 

      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) 
       type = Nullable.GetUnderlyingType(type); 

      dataTable.Columns.Add(propertyDescriptor.Name, type); 
     } 
     object[] values = new object[propertyDescriptorCollection.Count]; 
     foreach (T iListItem in iList) 
     { 
      for (int i = 0; i < values.Length; i++) 
      { 
       values[i] = propertyDescriptorCollection[i].GetValue(iListItem); 
      } 
      dataTable.Rows.Add(values); 
     } 
     return dataTable; 
    } 
+0

당신은 루프에 대한 귀하의 클래스에 데이터 주석을 사용하여 사람들을 테스트 할 수 당신이 이러한 주석이 특성을 발생할 때 계속 수 있습니다. –

+0

우수 아이디어, 모든 샘플 코드 – user584018

+0

사용하는 경우 : dataTable.Rows.Add (values); 배열 'values'는 데이터 테이블의 열과 동일한 순서 여야합니다. 데이터 테이블에 8 개의 열이 포함 된 경우 값에 데이터 테이블의 처음 5 개 열이 포함될 수 있습니다. 데이터 테이블의 마지막 3 열은 null로 채워집니다. 때로는 필드 유형이 널을 허용하지 않으면 널 (null)로 오류를 얻을 수 있습니다. UniqueKey 및/또는 PointToPointData가 배열 중간에 있으면 코드에 문제가 있습니다. 일반적으로 다음과 같은 dataTable.Rows.Add (새 개체 [] {input1, input2, input5, input6, input10}); – jdweng

답변

0

을 2 개 속성 "UniqueKey"& "PointToPointData"를 보내지 않으

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] 
public class DontShowMe : Attribute 
{ 
} 

다음 특성을 사용하여 클래스에 주석을 달 수 있습니다.

public class PointDataClone 
{ 
    public int DataId { get; set; } 
    [DontShowMe] 
    public string UniqueKey { get; set; } 
    public int Count { get; set; } 
    [DontShowMe] 
    public List<PointToPointData> PointToPointData { get; set; } 
} 

및 속성을 쿼리하도록 함수를 수정하십시오. 당신은 당신의 루프

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) type = Nullable.GetUnderlyingType(type); 

// test attribute to see if it is shown 
if (propertyDescriptor.Attributes.Contains(new DontShowMe())) continue; 

dataTable.Columns.Add(propertyDescriptor.Name, type); 

이제 데이터 테이블은 열이보다 개체가 많은 특성을 가지고 것이라는 사실을 처리해야합니다이 줄을 추가 추가하여 문

using System.ComponentModel; 

가 필요합니다. 나는 그 작은 세부 사항을 관리하기 위해 당신에게 맡길 것입니다. 이 도움이

희망,

마크

+0

감사합니다. Marc !!! – user584018

관련 문제