schoon
schoon

Reputation: 3324

How do I print values in c# subarray?

I am new to c# and I am trying to print a user defined structure. Code:

        var tracksArr = new[]
        {new
            {   vessel = GetVesselInfo(aisRecord.VesselId),
                points = new[]
                {   new
                    {   stampUtc = aisRecord.Time.ToString("yyyy-MM-ddTHH:mm:ssZ"),
        }}}}
   
        foreach (var item in tracksArr)
            {Console.WriteLine("qqq: " + item.ToString());}

which prints:

qqq: { vessel = { key = 123456,0, mmsi = 7891011, imo = 0 }, points = 
<>f__AnonymousType18`6[System.String,System.Double,System.Double...

what is this mysterious <>f__AnonymousType18 and how do I get the value of points?

Upvotes: 1

Views: 168

Answers (1)

Guru Stron
Guru Stron

Reputation: 141565

For each anonymous type with unique set of fields (the new { ... } statements in means creation of instance of anonymous type) compiler will generate a class, which name will look like <>f__AnonymousType18. This class has overridden ToString method, but arrays/collections - don't and point is an array, so by default ToString returns type name which is YourAnonymousTypeName[] for arrays. You can use string.Join to output your collection:

Console.WriteLine($"qqq: {{vessel = {item.vessel}, points = {string.Join(", ", item.points.Select(p => p.ToString()))}}}");

Or create/use another collection type for points which will have overridden ToString method which returns string with all elements:

public static class ext
{ 
    public static MyList<T> ToMyList<T>(this T[] arr)
    {
        return new MyList<T>(arr);
    }
}
public class MyList<T> : List<T>
{
    public MyList(T[] arr)
    {
        AddRange(arr);
    }
    
    public override string ToString()
    {
        return string.Join(",", this);
    }
}

var tracksArr = new[]
       {new
            {   vessel = 1,
                points = new[]
                {   new
                    {   stampUtc = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"),               }
                }
                .ToMyList()
            }               
        }; // prints "qqq: { vessel = 1, points = { stampUtc = 2020-06-24T14:58:08Z } }"

Upvotes: 2

Related Questions