Skip to content

Commit

Permalink
Merge pull request #151 from jinaga/render-table
Browse files Browse the repository at this point in the history
Notebook extension to render a collection as a table
  • Loading branch information
michaellperry authored Jan 13, 2025
2 parents b38c9ad + a1ee235 commit 00bcfa0
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
59 changes: 59 additions & 0 deletions Jinaga.Notebooks/DataFrameExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using Microsoft.Data.Analysis;

namespace Jinaga.Notebooks;

// Extension method to convert a list of objects into a DataFrame that the Notebook will display as a table.
public static class DataFrameExtensions
{
public static DataFrame AsTable<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));

var dataFrame = new DataFrame();
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

if (!properties.Any())
throw new InvalidOperationException($"Type {typeof(T).Name} has no public instance properties.");

// Create columns for each property
foreach (var prop in properties)
{
var propertyType = prop.PropertyType;
if (propertyType == typeof(string))
{
var values = source.Select(item => (string)prop.GetValue(item)).ToList();
dataFrame.Columns.Add(new StringDataFrameColumn(prop.Name, values));
}
else if (propertyType == typeof(int) || propertyType == typeof(int?))
{
var values = source.Select(item => (int?)prop.GetValue(item)).ToList();
dataFrame.Columns.Add(new Int32DataFrameColumn(prop.Name, values));
}
else if (propertyType == typeof(double) || propertyType == typeof(double?))
{
var values = source.Select(item => (double?)prop.GetValue(item)).ToList();
dataFrame.Columns.Add(new DoubleDataFrameColumn(prop.Name, values));
}
else if (propertyType == typeof(bool) || propertyType == typeof(bool?))
{
var values = source.Select(item => (bool?)prop.GetValue(item)).ToList();
dataFrame.Columns.Add(new BooleanDataFrameColumn(prop.Name, values));
}
else if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
{
var values = source.Select(item => (DateTime?)prop.GetValue(item)).ToList();
dataFrame.Columns.Add(new PrimitiveDataFrameColumn<DateTime>(prop.Name, values));
}
else
throw new NotSupportedException($"Property type {propertyType.Name} is not supported.");
}

return dataFrame;
}
}
1 change: 1 addition & 0 deletions Jinaga.Notebooks/Jinaga.Notebooks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Data.Analysis" Version="0.22.0" />
</ItemGroup>

<ItemGroup>
Expand Down

0 comments on commit 00bcfa0

Please sign in to comment.