gpt4 book ai didi

c# - 如何透视 IEnumerable

转载 作者:太空狗 更新时间:2023-10-29 20:40:48 25 4
gpt4 key购买 nike

我需要“转动”或“旋转”一组对象。该示例将清除我需要做的事情:

var people = new List<Person>(new[] {
new Person{ Name="Ronnie",Age=25, HairColor="Brown",EyeColor="Blue"},
new Person{ Name="Tina",Age=25, HairColor="Brown",EyeColor="Green"},
new Person{ Name="Lukus",Age=4, HairColor="Blonde",EyeColor="Blue"}
});

DataTable rotatedData = people.Pivot("Name", "Property");

/* Results In:
* ___________________________________________
* Property | Ronnie | Tina | Lukus
* ___________________________________________
* Age | 25 | 25 | 4
* HairColor | Brown | Brown | Blonde
* EyeColor | Blue | Green | Blue
* ____________________________________________
*/

这是我编写的实现此目的的代码:

/// <summary>Converts an IEnumerable into a pivoted DataTable object.</summary>
/// <param name="collection">The IEnumerable object to pivot and convert.</param>
/// <param name="headingMember">The name of a public field or property member of type T to be used as column name's in the pivoted DataTable object.</param>
/// <param name="membersHeading">The name of the column that lists the public fields and properties of type T.</param>
static DataTable Pivot<T>(this IEnumerable<T> collection, string headingMember, string membersHeading)
{
// get object information
var type = typeof(T);
var members = new List<MemberInfo>();
members.AddRange(type.GetProperties(BindingFlags.Public | BindingFlags.Instance));
members.AddRange(type.GetFields(BindingFlags.Public | BindingFlags.Instance));

// create dataTable and establish schema
var dt = new DataTable();
dt.Columns.Add(membersHeading);
foreach (var item in collection)
{
var member = members.Single(x => x.Name == headingMember);
if (member is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)member;
dt.Columns.Add(fieldInfo.GetValue(item).ToString(), fieldInfo.FieldType);
}

if (member is PropertyInfo)
{
PropertyInfo propInfo = (PropertyInfo)member;
dt.Columns.Add(propInfo.GetValue(item, null).ToString(), propInfo.PropertyType);
}
}

// add rows to table
foreach (MemberInfo member in members.Where(x => x.Name != headingMember))
{
var row = dt.NewRow();
row[0] = member.Name;
int i = 1;

foreach (var item in collection)
{
if (member is FieldInfo)
row[i++] = ((FieldInfo)member).GetValue(item);

if (member is PropertyInfo)
row[i++] = ((PropertyInfo)member).GetValue(item, null);
}

dt.Rows.Add(row);
}

return dt;
}

有没有 什么是更好的方法?

最佳答案

您可以简单地通过在名称上使用 Group 来对 IEnumerable 进行透视。假设名称是不同的。旋转数据后,您可以 Convert IEnumerable to DataTable .

关于c# - 如何透视 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1756839/

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