Raphael
Raphael

Reputation: 127

Get values out of collections with FastMember

I use FastMember to get values out of objects and nested objects. If a property is a string or int everything works fine. But now I want to get the values also for collections. Here is my code so far:

// Set accessor
var sourceAccessor = ObjectAccessor.Create(source);

if (sourceAccessor.Target.GetType().GetInterface(nameof(ICollection)) != null || sourceAccessor.Target.GetType().GetInterface(nameof(IEnumerable)) != null)
{
    foreach (/* idk */)
    {
        // READ & RETURN VALUES HERE
    }
}

An object could look like this:

{
Id: 1,
Surname: Doe,
Prename: John,
Professions: [
    { Name: ab },
    { Name: xy }
]
}

Which means professions would result in a problem.

Any advise how I can solve this problem? Thanks!

Upvotes: 0

Views: 772

Answers (1)

Pablissimo
Pablissimo

Reputation: 2905

It's not obvious from the question what the data type of the source variable is, but you should just be able to check if the value returned by the accessor implements IEnumerable or not and act accordingly.

Here's a quick worked example that iterates over the Professions property of a 'Person' object and just dumps the ToString() representation to the console - if you wanted to dive into each Profession object using FastMember you could construct another ObjectAccessor to do it, I guess - it's not clear what your goal is once you're iterating.

The same tactic will work if you're building the ObjectAccessor directly from an array - you just check if the accessor.Target is IEnumerable and cast-and-iterate in a similar fashion.

class Program
{
    static void Main(string[] args)
    {
        var p = new Person
        {
            Professions = new List<Profession>
            {
                new Profession("Joker"),
                new Profession("Smoker"),
                new Profession("Midnight toker")
            }
        };

        var accessor = ObjectAccessor.Create(p);
        var professions = accessor[nameof(Person.Professions)];

        if (professions is IEnumerable)
        {
            foreach (var profession in (IEnumerable)professions)
            {
                Console.WriteLine(profession);
            }
        }
    }
}

class Person
{
    public List<Profession> Professions { get; set; }
}

class Profession
{
    public string Name { get; set; }

    public Profession( string name)
    {
        Name = name;
    }

    public override string ToString()
    {
        return Name;
    }
}

Upvotes: 1

Related Questions