在下面的代码中,我将返回具有可变列数的数据。
因此它可以返回列#a; b,c,d,e'或者它可以返回列#a; b,c,g,m,n' - 设置前三列,但随后可能有任意数量的其他列。然后我需要将数据作为匿名类型列表返回。在下面的代码中,我展示了如何获取数据,转动它,并将列添加到ArrayList objDataColumn
,然后创建一个数据表,这确实让我接近,但我不是能够弄清楚如何将数据作为列表返回。
我希望让它返回一个匿名类型的通用列表,而不是让它返回datatable
行列表,而不是像以下那样(在这种情况下'属性'是唯一的动态专栏):
{ EntitlementId = 477653184, FileSetTypeID = 146, FileTypeCode = "test", SourceSystemKey = "userkey", Entitlement = "Chg Mgrs - AppDev Sour GUI", Attribute = "Change Manager" }
////Applying linq for geting pivot output
var d = (from f in result
group f by new { f.EntitlementId, f.FileSetTypeID, f.FileTypeCode, f.SourceSystemKey, f.Entitlement }
into myGroup
where myGroup.Count() > 0
select new
{
myGroup.Key.EntitlementId,
myGroup.Key.FileSetTypeID,
myGroup.Key.FileTypeCode,
myGroup.Key.SourceSystemKey,
myGroup.Key.Entitlement,
ColumnName = myGroup.GroupBy(f => f.ColumnName).Select(m => new { Col = m.Key, Value = m.Max(c => c.Value) })
}).ToList();
//PART 2 - Distinct ColumnName
var cols = (
from a in result
select new { ColumnName = a.ColumnName }
).Distinct().ToList();
//PART 3 - Creating array for adding dynamic columns
ArrayList objDataColumn = new ArrayList();
//Fixed columns
objDataColumn.Add("FileTypeCode");
objDataColumn.Add("SourceSystemKey");
objDataColumn.Add("Entitlement");
//Add Subject Name as column in Datatable
for (int i = 0; i < cols.Count; i++)
{
objDataColumn.Add(cols[i].ColumnName);
}
//Add dynamic columns name to datatable dt
DataTable dt = new DataTable();
for (int i = 0; i < objDataColumn.Count; i++)
{
dt.Columns.Add(objDataColumn[i].ToString());
}
//PART 4 - Add data into datatable with respect to dynamic columns and dynamic data
for (int i = 0; i < d.Count; i++)
{
List<string> tempList = new List<string>();
tempList.Add(result[i].FileTypeCode.ToString());
tempList.Add(result[i].SourceSystemKey.ToString());
tempList.Add(result[i].Entitlement.ToString());
var res = d[i].ColumnName.ToList();
for (int j = 0; j < res.Count; j++)
{
tempList.Add(res[j].Value.ToString());
}
dt.Rows.Add(tempList.ToArray<string>());
}
//END PIVOT
IEnumerable<DataRow> rows = dt.AsEnumerable();
在此先感谢,如果需要任何其他信息,请与我们联系,希望这不会太令人困惑。
答案 0 :(得分:1)
能够使用动态列表和ExpandoObject类来解决这个问题。 这是代码,希望它可以帮助其他人:
List<dynamic> dynList = new List<dynamic>();
for (int i = 0; i < d.Count; i++)
{
dynamic dynObj = new ExpandoObject();
((IDictionary<string, object>)dynObj).Add("FileTypeCode", result[i].FileTypeCode.ToString());
((IDictionary<string, object>)dynObj).Add("Fullname", result[i].Fullname.ToString());
((IDictionary<string, object>)dynObj).Add("Entitlement", result[i].Entitlement.ToString());
var res = d[i].ColumnName.ToList();
for (int j = 0; j < res.Count; j++)
{
((IDictionary<string, object>)dynObj).Add(res[j].Col.ToString(), res[j].Value.ToString());
}
dynList.Add(dynObj);
}
var dList = (from da in dynList select da).ToList();
return dList;