If you accept any type, that would also include IEnumerable<User>
and IEnumerable<Car>
, how would you expect to convert them to float and string? It would be much better to have an object that encapsulates a float and a string value, use an interface for that. For example, have an interface like this:
public interface IChartItem
{
float Value { get; set; }
string Label { get; set; }
}
An example class:
public class Foo : IChartItem
{
public int MyProperty { get; set; }
public string Name { get; set; }
public float Value => (float)MyProperty;
public string Label => Name;
}
And now your function could be generic with a constraint:
public void ChartData<T>(IEnumerable<T> items)
where T : IChartItem
{
this.values = items.Select(x => x.Value);
this.labels = items.Select(x => x.Label);
}
Alternative Option
You could also pass in your object along with a couple of Func
parameters to get the value and label. For example:
public void ChartData<T>(IEnumerable<T> items,
Func<T, float> valueSelector,
Func<T, string> labelSelector)
{
this.values = items.Select(x => valueSelector(x));
this.labels = items.Select(x => labelSelector(x));
}
And use it like this:
ChartData(foos, f => (float)f.MyProperty, f => f.Name);