gpt4 book ai didi

c# - 遍历匿名类型列表的对象属性

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:03 24 4
gpt4 key购买 nike

我正在使用 EPPlus 创建一个“导出到 Excel”助手。这基本上会采用匿名列表并使用该列表来填充电子表格。

我希望能够遍历列表对象的属性并确定哪个是 datetime 并适本地设置该列的格式。我在下面的代码有效,但是是否有更简洁的方式来编写它 - 特别是在我不依赖于从列表中拉出对象并对该对象进行操作的地方(即我从列表本身获取属性类型)?

    private static string[] columnIndex = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".Split(',');
private static ExcelWorksheet CreateAndFormatWorksheet<T>(OfficeOpenXml.ExcelPackage pck, List<T> dataSet)
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Monet_Export_" + DateTime.Now.ToString());
ws.Cells["A1"].LoadFromCollection(dataSet, true);

if (dataSet.Count > 0)
{
// Pull first list item to determine so we have something to iterate over below
dynamic first = dataSet[0];

// List count == upper row count for the spreadsheet
string rowCount = dataSet.Count.ToString();

int i = 0;
foreach (PropertyInfo info in first.GetType().GetProperties())
{
if (info.PropertyType == typeof(DateTime))
{
string column = columnIndex[i];
string indexer = column + "2:" + column + rowCount;
ws.Cells[indexer].Style.Numberformat.Format = "mm/dd/yyyy";
}
else if (info.PropertyType == typeof (int))
{
string column = columnIndex[i];
string indexer = column + "2:" + column + rowCount;
ws.Cells[indexer].Style.Numberformat.Format = "@";
}

i++;
}
}

return ws;
}

最佳答案

您可以使用 typeof(T).GetProperties() 获取类型 T 的属性。这也适用于匿名类型。

然后你不需要拉出第一个项目来检查它的属性,你也不必检查 dataSet.Count > 0(如果你想允许一个空的电子表格).

关于c# - 遍历匿名类型列表的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29357229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com