将一个字符串列表写入控制台

时间:2014-03-08 09:31:33

标签: c# .net google-api google-analytics-api google-api-client

我试图将一个字符串列表写入控制台但得到此输出: 的 System.Collections.Generic.List`1 [System.String]

我想我可能正在编写错误的代码,或者我需要以某种方式转换它。

这就是我的列表的样子(Rows是GaData类中的属性和字符串列表):

List<string> ListDates = new List<string>(new string[] { d.Rows.ToString()});

Console.WriteLine(ListDates);
Console.ReadLine();

这是GaData类的属性:

public virtual IList<IList<string>> Rows { get; set; }

我正在检索从Google AnalyticsAPI收集的一些数据。我试图使用该物业&#34; Rows&#34;来自谷歌GaData类是一个字符串列表。行还包含更多的Vaule,如StartDate,EndDate,Visitors,NewVisits,Pageview,PercentNewVisits,所有这些参数都是keyValuePair的值。例如:

KeyValuePair访客: key =&#34; ga:访客&#34; value = 3000(实际访客人数)。

调试时获得的数据:

enter image description here

从谷歌获得GaData类:

enter image description here

这是来自Google的KeyValuePairs课程。它使用指标,维度和排序来过滤来自谷歌API的数据。例如:metrics =&#34;访问者&#34;,Demensions =&#34; ga:date&#34;,sort =&#34; ga:visits&#34;。 enter image description here

不知道它是否有必要,但这里是代码:

我的Google API客户端:

public static void Main(string[] args)
            {
                var serviceAccountEmail = "User@developer.gserviceaccount.com";

                var certificate = new X509Certificate2(@"C:\Users\User\Desktop\key.p12", "notasecret", X509KeyStorageFlags.Exportable);




                var credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = new[] { AnalyticsService.Scope.Analytics }
                }.FromCertificate(certificate));

                // Create the service.
                //Twistandtango
                var gas = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "TestGoogleAnalytics",
                });

                var r = gas.Data.Ga.Get("ProfileID", "2014-01-24", "2014-02-28", "ga:pageviews,ga:newVisits,ga:visitors,ga:percentNewVisits");


                r.Dimensions = "ga:date";
                r.Sort = "-ga:date";
                r.MaxResults = 10000;



                //Execute and fetch the results of our query
                Google.Apis.Analytics.v3.Data.GaData d = r.Execute();



                //output Rows with all visitor data for each date between StartDate and EndDate
                List<string> ListDates = new List<string>(new string[] { d.Rows.ToString()});

                Console.WriteLine(ListDates);
                Console.ReadLine();





                //Output actuall values - visitors, newVisits, pageviews and percentNewVisits
                Console.WriteLine("Besöksstatistik" + "  " + 
                    d.Query.StartDate + " " + "-" + " " + d.Query.EndDate + "\r\n" +
                    "------------------------------------------" + "\r\n" +
                 "Antal besökare:" + " " + d.TotalsForAllResults["ga:visitors"] + "\r\n" +
                 "Antal nya besökare:" + " " + d.TotalsForAllResults["ga:newVisits"] + "\r\n" +
                 "Sidvisningar:" + " " + d.TotalsForAllResults["ga:pageviews"] + "\r\n" +
                 "Procent nya besökare:" + " " + d.TotalsForAllResults["ga:percentNewVisits"] +"%");


                Console.ReadLine();

GaData class(Google):

    public class GaData : IDirectResponseSchema
    {
        public GaData();

        // Summary:
        //     Column headers that list dimension names followed by the metric names. The
        //     order of dimensions and metrics is same as specified in the request.
        [JsonProperty("columnHeaders")]
        public virtual IList<GaData.ColumnHeadersData> ColumnHeaders { get; set; }
        //
        // Summary:
        //     Determines if Analytics data contains samples.
        [JsonProperty("containsSampledData")]
        public virtual bool? ContainsSampledData { get; set; }
        [JsonProperty("dataTable")]
        public virtual GaData.DataTableData DataTable { get; set; }
        //
        // Summary:
        //     The ETag of the item.
        public virtual string ETag { get; set; }
        //
        // Summary:
        //     Unique ID for this data response.
        [JsonProperty("id")]
        public virtual string Id { get; set; }
        //
        // Summary:
        //     The maximum number of rows the response can contain, regardless of the actual
        //     number of rows returned. Its value ranges from 1 to 10,000 with a value of
        //     1000 by default, or otherwise specified by the max-results query parameter.
        [JsonProperty("itemsPerPage")]
        public virtual int? ItemsPerPage { get; set; }
        //
        // Summary:
        //     Resource type.
        [JsonProperty("kind")]
        public virtual string Kind { get; set; }
        //
        // Summary:
        //     Link to next page for this Analytics data query.
        [JsonProperty("nextLink")]
        public virtual string NextLink { get; set; }
        //
        // Summary:
        //     Link to previous page for this Analytics data query.
        [JsonProperty("previousLink")]
        public virtual string PreviousLink { get; set; }
        //
        // Summary:
        //     Information for the view (profile), for which the Analytics data was requested.
        [JsonProperty("profileInfo")]
        public virtual GaData.ProfileInfoData ProfileInfo { get; set; }
        //
        // Summary:
        //     Analytics data request query parameters.
        [JsonProperty("query")]
        public virtual GaData.QueryData Query { get; set; }
        //
        // Summary:
        //     Analytics data rows, where each row contains a list of dimension values followed
        //     by the metric values. The order of dimensions and metrics is same as specified
        //     in the request.
        [JsonProperty("rows")]
        public virtual IList<IList<string>> Rows { get; set; }
        //
        // Summary:
        //     The number of samples used to calculate the result.
        [JsonProperty("sampleSize")]
        public virtual long? SampleSize { get; set; }
        //
        // Summary:
        //     Total size of the sample space from which the samples were selected.
        [JsonProperty("sampleSpace")]
        public virtual long? SampleSpace { get; set; }
        //
        // Summary:
        //     Link to this page.
        [JsonProperty("selfLink")]
        public virtual string SelfLink { get; set; }
        //
        // Summary:
        //     The total number of rows for the query, regardless of the number of rows
        //     in the response.
        [JsonProperty("totalResults")]
        public virtual int? TotalResults { get; set; }
        //
        // Summary:
        //     Total values for the requested metrics over all the results, not just the
        //     results returned in this response. The order of the metric totals is same
        //     as the metric order specified in the request.
        [JsonProperty("totalsForAllResults")]
        public virtual IDictionary<string, string> TotalsForAllResults { get; set; }

以下是Google类,其中包含用于过滤API数据的参数:

 // Summary:
            //     Returns Analytics data for a view (profile).
            public class GetRequest : AnalyticsBaseServiceRequest<Google.Apis.Analytics.v3.Data.GaData>
            {
                // Summary:
                //     Constructs a new Get request.
                public GetRequest(IClientService service, string ids, string startDate, string endDate, string metrics);

                // Summary:
                //     A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'.
                [RequestParameter("dimensions", RequestParameterType.Query)]
                public virtual string Dimensions { get; set; }
                //
                // Summary:
                //     End date for fetching Analytics data. Request can should specify an end date
                //     formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or
                //     7daysAgo). The default value is yesterday.
                [RequestParameter("end-date", RequestParameterType.Query)]
                public virtual string EndDate { get; }
                //
                // Summary:
                //     A comma-separated list of dimension or metric filters to be applied to Analytics
                //     data.
                [RequestParameter("filters", RequestParameterType.Query)]
                public virtual string Filters { get; set; }
                //
                // Summary:
                //     Gets the HTTP method.
                public override string HttpMethod { get; }
                //
                // Summary:
                //     Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX,
                //     where XXXX is the Analytics view (profile) ID.
                [RequestParameter("ids", RequestParameterType.Query)]
                public virtual string Ids { get; }
                //
                // Summary:
                //     The maximum number of entries to include in this feed.
                [RequestParameter("max-results", RequestParameterType.Query)]
                public virtual int? MaxResults { get; set; }
                //
                // Summary:
                //     Gets the method name.
                public override string MethodName { get; }
                //
                // Summary:
                //     A comma-separated list of Analytics metrics. E.g., 'ga:visits,ga:pageviews'.
                //     At least one metric must be specified.
                [RequestParameter("metrics", RequestParameterType.Query)]
                public virtual string Metrics { get; }
                //
                // Summary:
                //     The selected format for the response. Default format is JSON.
                [RequestParameter("output", RequestParameterType.Query)]
                public virtual DataResource.GaResource.GetRequest.OutputEnum? Output { get; set; }
                //
                // Summary:
                //     Gets the REST path.
                public override string RestPath { get; }
                //
                // Summary:
                //     The desired sampling level.
                [RequestParameter("samplingLevel", RequestParameterType.Query)]
                public virtual DataResource.GaResource.GetRequest.SamplingLevelEnum? SamplingLevel { get; set; }
                //
                // Summary:
                //     An Analytics advanced segment to be applied to data.
                [RequestParameter("segment", RequestParameterType.Query)]
                public virtual string Segment { get; set; }
                //
                // Summary:
                //     A comma-separated list of dimensions or metrics that determine the sort order
                //     for Analytics data.
                [RequestParameter("sort", RequestParameterType.Query)]
                public virtual string Sort { get; set; }
                //
                // Summary:
                //     Start date for fetching Analytics data. Requests can specify a start date
                //     formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or
                //     7daysAgo). The default value is 7daysAgo.
                [RequestParameter("start-date", RequestParameterType.Query)]
                public virtual string StartDate { get; }
                //
                // Summary:
                //     An index of the first entity to retrieve. Use this parameter as a pagination
                //     mechanism along with the max-results parameter.
                [RequestParameter("start-index", RequestParameterType.Query)]
                public virtual int? StartIndex { get; set; }

                // Summary:
                //     Initializes Get parameter list.
                protected override void InitParameters();

                // Summary:
                //     The selected format for the response. Default format is JSON.
                public enum OutputEnum
                {
                    // Summary:
                    //     Returns the response in Google Charts Data Table format. This is useful in
                    //     creating visualization using Google Charts.
                    [StringValue("dataTable")]
                    DataTable = 0,
                    //
                    // Summary:
                    //     Returns the response in standard JSON format.
                    [StringValue("json")]
                    Json = 1,
                }

                // Summary:
                //     The desired sampling level.
                public enum SamplingLevelEnum
                {
                    // Summary:
                    //     Returns response with a sample size that balances speed and accuracy.
                    [StringValue("DEFAULT")]
                    DEFAULT = 0,
                    //
                    // Summary:
                    //     Returns a fast response with a smaller sample size.
                    [StringValue("FASTER")]
                    FASTER = 1,
                    //
                    // Summary:
                    //     Returns a more accurate response using a large sample size, but this may
                    //     result in the response being slower.
                    [StringValue("HIGHER_PRECISION")]
                    HIGHERPRECISION = 2,
                }
            }
        }

我要归档的是:

enter image description here

我的确实问题是我如何能够显示来自&#34; Rows&#34; GaData类中的属性。尽管如此,你可能会比我更多地了解这一点以及更好的解决方案,以便在控制台中显示数据。

我会非常感谢你的帮助!!

谢谢

// CHRISS

4 个答案:

答案 0 :(得分:0)

内部列表只需要一个循环:

List<string> ListDates = new List<string>(new string[] { d.Rows.ToString()});

foreach(var str in list){
    Console.WriteLine(str);
}

Console.ReadLine();

同时检查String.Format静态方法,以便您可以很好地格式化字符串(在完成列表时可以使用它代替d.Rows.ToString)

答案 1 :(得分:0)

尝试这样的事情:

例如,每行中的访客。如你所说,每一行都有属性对吗?比如访问者,每个访问者都有键/值对。

foreach (var row in d.Rows)
{
    Console.WriteLine(string.Format("Visitors: {0}, Visits: {1}", row.Visitors.Key, row.Visitors.Value));
}

答案 2 :(得分:0)

当你回到代码中时,foreach肯定是最明确和最明显的,但如果你真的想在一行上使用它,你可以使用一些LINQ魔法......这是实现同样事情的两种方式。

        var values = new List<string> { "a", "b", "c" };

        foreach (var v in values)
            Console.WriteLine(v);

        Console.WriteLine(values.Aggregate("", (current, next) => current + Environment.NewLine + next));

请记住为Aggregate包含System.Linq。

在任何一种情况下,您都需要深入了解Rows属性,因为它是一个嵌套的IList。所以你需要加倍使用foreach或Aggregate,例如

        var values = new List<List<string>> { new List<string>{"a", "b"}, new List<string>{"c"} };

        foreach (var v in values)
        foreach (var innerValue in v)
        Console.WriteLine(innerValue);

        Console.WriteLine(values.Aggregate("", (current, next) => current + Environment.NewLine + next.Aggregate("", (c, n) => c + Environment.NewLine + n).Trim(new []{'\r', '\n'})));

答案 3 :(得分:-1)

您可以在https://developers.google.com/apis-explorer/#search/analytics/analytics/v3/analytics.data.ga.get

下获取有关查询结果的信息

d.Rows[0][0]向您显示查询的第一个结果,我会这样输出:

Console.WriteLine("{0}: {1}", d.ColumnHeaders[0].Name, d.Rows[0][0]);