minhhungit / ConsoleTableExt

A fluent library to print out a nicely formatted table in a console application C#
MIT License
323 stars 36 forks source link

List<T> Not Renderining #22

Closed Chiliyago closed 3 years ago

Chiliyago commented 3 years ago

The following code returns nothing. Seems similar to the Sample code you have but not sure yet what the problem is with this code.

public class Dog
{
    public string Name = "Fido";
    public string Breed = "Doberman";
    public int Age = 4;
}
List<Dog> dogList = new List<Dog>();
    dogList.Add(new Dog()
        { Name = "spike", Breed = "Poodle", Age = 3 });

    dogList.Add(new Dog()
        { Name = "george", Breed = "Spaniel", Age = 8 });

    dogList.Add(new Dog()
        { Name = "sammy", Breed = "Weimaraner", Age = 13 });

ConsoleTableBuilder
    .From(dogList)
    .WithFormat(ConsoleTableBuilderFormat.Minimal).ExportAndWriteLine();
Chiliyago commented 3 years ago

This may be because I am targeting .net Core 3.1??

minhhungit commented 3 years ago

Hi @Chiliyago Your Dog class should be like this:

public class Dog
{
    public string Name { get; set; } = "Fido";
    public string Breed { get; set; } = "Doberman";
    public int Age { get; set; } = 4;
}

It just support property, not field

minhhungit commented 3 years ago

In case you still want to use your Dog class for some reason (maybe you don't want to modify current code) you can wrap the class, like this, here I create new DogWrap and it will wrap Dog

public class Dog
{
    public string Name = "Fido";
    public string Breed  = "Doberman";
    public int Age = 4;
}

public class DogWrap
{
    public DogWrap(Dog dog)
    {
        if (dog != null)
        {
            this.Name = dog.Name;
            this.Breed = dog.Breed;
            this.Age = dog.Age;
        }                
    }

    public string Name { get; set; }
    public string Breed { get; set; }
    public int Age { get; set; }
}

and use it:

List<Dog> dogList = new List<Dog>();
dogList.Add(new Dog() { Name = "spike", Breed = "Poodle", Age = 3 });

dogList.Add(new Dog() { Name = "george", Breed = "Spaniel", Age = 8 });

dogList.Add(new Dog() { Name = "sammy", Breed = "Weimaraner", Age = 13 });

var wrappedDogs = dogList.Select(x => new DogWrap (x)).ToList(); // add this line

ConsoleTableBuilder
    .From(wrappedDogs)
    .WithFormat(ConsoleTableBuilderFormat.Minimal).ExportAndWriteLine();

Hope it helps

Chiliyago commented 3 years ago

Thank you! That fixed it.