문제

내 앱에 채우는 메서드가 있습니다. DataTable 다음 코드를 사용하여 데이터를 사용합니다.

DataTable dt = this.attachmentsDataSet.Tables["Attachments"];

foreach (Outlook.Attachment attachment in this.mailItem.Attachments)
{
    DataRow dr = dt.NewRow();
    dr["Index"] = attachment.Index;
    dr["DisplayName"] = String.Format(
        CultureInfo.InvariantCulture,
        "{0} ({1})", 
        attachment.FileName,
        FormatSize(attachment.Size));
    dr["Name"] = attachment.FileName;
    dr["Size"] = attachment.Size;

    dt.Rows.Add(dr);
}

이 코드를 조금 단축하기 위해 LINQ를 사용하여 동일한 기능을 얻을 수 있는지 궁금합니다.어떤 아이디어가 있나요?

도움이 되었습니까?

해결책

글쎄,이 코드는 짧거나 LINQ가 아니지만 ILIST를 취하여 데이터 가능성으로 바꾸는 외부 세션 방법을 수행했습니다.

    public static DataTable ToDataTable<T>(this IList<T> theList)
    {
        DataTable theTable = CreateTable<T>();
        Type theEntityType = typeof(T);

        // Use reflection to get the properties of the generic type (T)
        PropertyDescriptorCollection theProperties = TypeDescriptor.GetProperties(theEntityType);

        // Loop through each generic item in the list
        foreach (T theItem in theList)
        {
            DataRow theRow = theTable.NewRow();

            // Loop through all the properties
            foreach (PropertyDescriptor theProperty in theProperties)
            {
                // Retrieve the value and check to see if it is null
                object thePropertyValue = theProperty.GetValue(theItem);
                if (null == thePropertyValue)
                {
                    // The value is null, so we need special treatment, because a DataTable does not like null, but is okay with DBNull.Value
                    theRow[theProperty.Name] = DBNull.Value;
                }
                else
                {
                    // No problem, just slap the value in
                    theRow[theProperty.Name] = theProperty.GetValue(theItem);
                }
            }

            theTable.Rows.Add(theRow);
        }

        return theTable;
    }

다른 팁

예, 쉽습니다

    public void FillFromList(List<T> col)
    {
        Type elementType = typeof(T);

        // Nested query of generic element list of property
        // values (using a join to the DataTable columns)
        var rows = from row in col
                   select new
                   {
                       Fields = from column in m_dataTable.Columns.Cast<DataColumn>()
                                join prop in elementType.GetProperties()
                                  on column.Caption equals prop.Name
                                select prop.GetValue(row, null)
                   };

        // Add each row to the DataTable
        int recordCount = 0;
        foreach ( var entry in rows )
        {
            m_dataTable.Rows.Add(entry.Fields.ToArray());
        }

이것은 t의 속성이 데이터 가능한 열과 동일하다고 가정합니다.

먼저 쿼리할 수 있는지 확인합니다. this.mailItem.Attachments 가능하다면 쿼리 결과를 생성 한 Extension Method의 데이터 가능로 변환 할 수 있습니다. 스티브 슬로카...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top