【问题标题】:Write a List of strings to the Console将字符串列表写入控制台
【发布时间】:2014-03-08 09:31:33
【问题描述】:

我试图将字符串列表写入控制台,但得到以下输出: 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 Analytics API 收集的一些数据。我试图使用来自 google GaData 类的属性“Rows”,它是一个字符串列表。 Rows 还包含更多的值,例如 StartDate、EndDate、Visitors、NewVisits、Pageviews、PercentNewVisits,所有这些参数都是 keyValuePair 的值。例如:

KeyValuePair 访问者: key = "ga:visitors" value =3000(实际访问人数)。

她调试时得到的数据:

她的来自 google 的 GaData 类:

这是来自 Google 的 KeyValuePairs 类。它使用指标、维度和排序来过滤来自 google api 的数据。例如:metrics="visitors"、Demensions="ga:date"、sort="ga:visits"。

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

我的 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 类(谷歌):

    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,
                }
            }
        }

我不想归档的是:

我的实际问题是如何在 GaData 类中显示“行”属性中的数据。尽管您可能比 i 更能理解这一点,并且是让数据显示在控制台中的更好解决方案。

如果能得到任何帮助,我将不胜感激!

谢谢

//克里斯

【问题讨论】:

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


    【解决方案1】:

    试试这样的:

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

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

    【讨论】:

    • 是的,像这样的东西可能是解决方案!然而“行”是一个属性 -public virtual IList> Rows { get;放; } 包含字典。例如,“visitors”的字典有 key="ga:visitors" 和 value="1000"(访客人数。
    • 是的,每一行都是一个字典,这就是为什么使用这个 foreach 循环,行将是一个 KeyValuePair,其中包含键和值,row.Visitors.Key 将是 ga:visitors 和 row.Visitors .Value 将是 1000 ;)
    • 好吧,我明白你的意思。我将围绕这个概念进行游戏,看看会发生什么。谢谢! =)
    • 我希望这对克里斯托弗有所帮助! ;)
    【解决方案2】:

    您可以在以下位置获取有关查询结果的信息: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]);
    

    【讨论】:

      【解决方案3】:

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

      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)

      【讨论】:

      • 我明白了,谢谢。我现在确实得到了一个列表,但输出仍然是 System.Collection.Generic.List`1[System.String] 但垂直。这是一张图片imageshack.com/i/e9tabpp
      【解决方案4】:

      当您回到代码时,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));
      

      请记住为聚合包含 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'})));
      

      【讨论】:

      • 这是一个非常有趣的输入。感谢您的解释,我将深入研究这个主题,看看我能想出什么。谢谢!但奇怪的是,Rows 包含我要向 Google 查询的所有数据 - StartDate、EndDate、访客、日期等但是我似乎无法单独访问它们。例如,如果我写 d.TotalsForAllResults["ga:visitors"] 我将得到输出“ga:visitors 3500”,其中 ga:visitors 是键,3500 是值,例如字典。但是,我无法使用 d.Rows 获得此输出
      猜你喜欢
      • 2011-08-10
      • 2020-09-12
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多