WebAPIContrib.Core icon indicating copy to clipboard operation
WebAPIContrib.Core copied to clipboard

Csv output formatter fails when Linq chain

Open twsouthwick opened this issue 5 years ago • 1 comments

I am using v3.0.0 of the Csv output formatter. However, I saw the following issue:

[Route("a")]
[HttpGet]
[Produces("text/csv")]
public IEnumerable<A> GetA()
{
    var b = new[]
    {
        new B { Item2 = "Hello" },
    };
    var result = b.Select(i => new A { Item1 = i.Item2 });

    return result;

    // If I replace the return with the following it works as expected:
    // return result.ToList();
}

public class A
{
    public string Item1 { get; set; }
}

private class B
{
    public string Item2 { get; set; }
}

The result of this is:

Item2
Hello

when I would expect

Item1
Hello

twsouthwick avatar Apr 02 '20 17:04 twsouthwick

This test is wrong.

Many linq operations return a class with multiple generic type arguments. Starting with the source type, not the result type.

Rather than .GetType(), you should locate the IEnumerable<T> interface and extract the generic type from there.

.GetType()
.GetInterfaces()
.Where(x =>
  x.IsGenericType &&
  x.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.FirstOrDefault()
?.GetGenericArguments()[0];

lakeman avatar Apr 11 '22 06:04 lakeman