【问题标题】:How can I create List of Lists and add to it items and then read back the items?如何创建列表列表并添加项目,然后读回项目?
【发布时间】:2017-01-15 19:43:56
【问题描述】:

一流的

public static List<string> countriescodes = new List<string>();
public static List<string> countriesnames = new List<string>();
public static List<List<string>> imagesUrls = new List<List<string>>();

在类构造函数中

public void Init()
{
    if (!File.Exists(@"c:\temp\countriesandcodes.txt"))
    {
         w = new StreamWriter(@"c:\temp\countriesandcodes.txt");
    }
    else
    {
         lines = File.ReadAllLines(@"c:\temp\countriesandcodes.txt");
    }

    foreach (string countrycode in lines)
    {
         if (countrycode.Contains("Code"))
         {
             string code = countrycode.Substring(15);
             countriescodes.Add(code);
         }
         else
         {
             string code = countrycode.Substring(15);
             countriesnames.Add(code);
         }
    }

    foreach (string cc in countriescodes)
    {
         ExtractDateAndTime("http://www.sat24.com/image2.ashx?region=" + cc);
    }
    ImagesLinks();
}

然后在图片链接中

public void ImagesLinks()
{
     int cnt = 0;
     foreach (string countryCode in countriescodes)
      {
          cnt++;
          for (; cnt < DatesAndTimes.Count(); cnt++)
          {
              string imageUrlIrTrue = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "true";
              string imageUrlIrFalse = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "false";
              imagesUrls.Add(imageUrlIrTrue);
              imagesUrls.Add(imageUrlIrFalse);
              if (cnt % 10 == 0) break;
           }
      }
 }

在imagesUrls 中,我想将每个countryName 添加到列表中。 例如在imagesUrls 中,我将有第一个这样格式的列表:每个列表中的第一项将是国家名称,然后从每个国家名称的国家代码列表构建链接。

Turkey

link1
link2
.
.
.
link9

那么imagesUrls中的分机List将是

Europe

link1
link2
.
.
.
link9

我想要的是在imagesUrls 中创建列表,每个列表的顶部首先包含countriesnames 列表中的国家/地区名称,然后使用countriescodes 列表使用imageUrlIrTrue 包含该国家/地区的链接和imageUrlIrFalse

然后在Form1我想阅读每个List和每个List的项目。

这是文件 countryandcodes.txt 的一部分,用于查看其格式: 我想做的一般是在form1中使用这个类,这样我就可以轻松获取每个国家,并且所有链接都使用国家代码和国家名称列表。

Country Code = eu
Country Name = Europe
Country Code = alps
Country Name = Alps
Country Code = nl
Country Name = Benelux
Country Code = de
Country Name = Germany
Country Code = sp
Country Name = Spain & Portugal
Country Code = fr
Country Name = France

这是该类的完整代码。也许这样看会更容易。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Xml;
using HtmlAgilityPack;
using System.ComponentModel;

namespace SatelliteImages
{
    class ExtractImages
    {
        static WebClient client;
        static string htmltoextract;
        public static List<string> countriescodes = new List<string>();
        public static List<string> countriesnames = new List<string>();
        public static List<string> DatesAndTimes = new List<string>();
        public static List<List<string>> imagesUrls = new List<List<string>>();

        static string firstUrlPart = "http://www.sat24.com/image2.ashx?region=";
        static string secondUrlPart = "&time=";
        static string thirdUrlPart = "&ir=";
        StreamWriter w;
        string[] lines;

        public bool WebProblem = false;

        public void Init()
        {
            if (!File.Exists(@"c:\temp\countriesandcodes.txt"))
            {
                w = new StreamWriter(@"c:\temp\countriesandcodes.txt");
            }
            else
            {
                lines = File.ReadAllLines(@"c:\temp\countriesandcodes.txt");
            }

            foreach (string countrycode in lines)
            {
                if (countrycode.Contains("Code"))
                {
                    string code = countrycode.Substring(15);
                    countriescodes.Add(code);
                }
                else
                {
                    string code = countrycode.Substring(15);
                    countriesnames.Add(code);
                }
            }

            foreach (string cc in countriescodes)
            {
                ExtractDateAndTime("http://www.sat24.com/image2.ashx?region=" + cc);
            }
            ImagesLinks();
        }     

        public void ExtractCountires()
        {
            try
            {
                htmltoextract = "http://sat24.com/en/?ir=true";//"http://sat24.com/en/";// + regions;
                client = new WebClient();
                client.DownloadFile(htmltoextract, @"c:\temp\sat24.html");
                client.Dispose();

                string tag1 = "<li><a href=\"/en/";
                string tag2 = "</a></li>";

                string s = System.IO.File.ReadAllText(@"c:\temp\sat24.html");
                s = s.Substring(s.IndexOf(tag1));
                s = s.Substring(0, s.LastIndexOf(tag2) + tag2.ToCharArray().Length);
                s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");

                string[] parts = s.Split(new string[] { tag1, tag2 }, StringSplitOptions.RemoveEmptyEntries);


                string tag3 = "<li><ahref=\"/en/";

                for (int i = 0; i < parts.Length; i++)
                {
                    if (i == 40)
                    {
                        break;
                    }
                    string l = "";
                    if (parts[i].Contains(tag3))
                        l = parts[i].Replace(tag3, "");

                    if (i == 39)
                    {
                        string fff = "";
                    }
                    string z1 = l.Substring(0, l.IndexOf('"'));
                    if (z1.Contains("</ul></li><liclass="))
                    {
                        z1 = z1.Replace("</ul></li><liclass=", "af");
                    }
                    countriescodes.Add(z1);
                    countriescodes.GroupBy(n => n).Any(c => c.Count() > 1);

                    string z2 = parts[i].Substring(parts[i].LastIndexOf('>') + 1);
                    if (z2.Contains("&amp;"))
                    {
                        z2 = z2.Replace("&amp;", " & ");
                    }
                    countriesnames.Add(z2);
                    countriesnames.GroupBy(n => n).Any(c => c.Count() > 1);
                }

                for (int i = 0; i < countriescodes.Count; i++)
                {
                    w.WriteLine("Country Code = " + countriescodes[i]);
                    w.WriteLine("Country Name = " + countriesnames[i]);
                }
                w.Close();
            }
            catch (Exception e)
            {
                if (countriescodes.Count == 0)
                {
                    /*countriescodes = new List<string>();
                    countriesnames = new List<string>();
                    DatesAndTimes = new List<string>();
                    imagesUrls = new List<string>();
                    Init();*/
                }
            }
        }

        public void ExtractDateAndTime(string baseAddress)
        {
            try
            {
                var wc = new WebClient();
                wc.BaseAddress = baseAddress;
                HtmlDocument doc = new HtmlDocument();

                var temp = wc.DownloadData("/en");
                doc.Load(new MemoryStream(temp));

                var secTokenScript = doc.DocumentNode.Descendants()
                    .Where(e =>
                           String.Compare(e.Name, "script", true) == 0 &&
                           String.Compare(e.ParentNode.Name, "div", true) == 0 &&
                           e.InnerText.Length > 0 &&
                           e.InnerText.Trim().StartsWith("var region")
                          ).FirstOrDefault().InnerText;
                var securityToken = secTokenScript;
                securityToken = securityToken.Substring(0, securityToken.IndexOf("arrayImageTimes.push"));
                securityToken = secTokenScript.Substring(securityToken.Length).Replace("arrayImageTimes.push('", "").Replace("')", "");
                var dates = securityToken.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                var scriptDates = dates.Select(x => new ScriptDate { DateString = x });
                foreach (var date in scriptDates)
                {
                    DatesAndTimes.Add(date.DateString);
                }
            }
            catch(WebException wex)
            {
                WebProblem = true;
            }
        }

        public class ScriptDate
        {
            public string DateString { get; set; }
            public int Year
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(0, 4));
                }
            }
            public int Month
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(4, 2));
                }
            }
            public int Day
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(6, 2));
                }
            }
            public int Hours
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(8, 2));
                }
            }
            public int Minutes
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(10, 2));
                }
            }
        }

        public void ImagesLinks()
        {
            int cnt = 0;
            foreach (string countryCode in countriescodes)
            {
                cnt++;
                for (; cnt < DatesAndTimes.Count(); cnt++)
                {
                    string imageUrlIrTrue = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "true";
                    string imageUrlIrFalse = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "false";
                    imagesUrls.Add(imageUrlIrTrue);
                    imagesUrls.Add(imageUrlIrFalse);
                    if (cnt % 10 == 0) break;
                }
            }
        }
    }
}

我现在尝试向班级添加一个班级

public class Country
        {
            public List<Tuple<Uri, bool>> URLList { get; set; }
            public string Code { get; set; }
        }

不确定如何使用属性代码。 我在列表中添加了一个布尔值,因为我想这样做,当我在 form1 中循环列表时,我将拥有真假链接,就像我在 ImagesLinks 方法中所做的那样:

string imageUrlIrTrue = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "true";
string imageUrlIrFalse = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "false";

但也许改为在 List 中使用 bool 并使其成为 Tuple 我应该将其更改回 List 并以其他方式使用 bool 来构建链接。

一般来说,我希望在 form1 中我能够获得 3 个参数:

  1. 图片链接。

  2. 国家代码。

  3. 链接应该是真假而不是布尔值,而是作为链接的一部分,例如:

imageUrlIrTrue:

http://www.sat24.com/image2.ashx?region=is&time=201701161900&ir=true

假的:

http://www.sat24.com/image2.ashx?region=is&time=201701161900&ir=false

每个国家都有 9 个由国家代码和日期和时间组成的链接。 所以在form1中我应该有一个类似List的东西。 例如,Country 类应该有一个属性,如果我在 form1 中输入该属性:Country.Country.Turkey

然后我应该还有土耳其的 9 个链接和土耳其的代码。

不仅要获取国家和代码,而且每个国家/地区的每9个链接实际上每个国家/地区有18个链接,因为每个链接都是双真/假。

所以每个国家都有 18 个链接!我应该能够在 form1 中循环访问它们,还可以访问国家代码和名称。

所以在 form1 中我应该有一个循环,我可以轻松获取国家名称获取每个国家/地区 18 个链接(真假)和每个国家/地区代码!!!

【问题讨论】:

  • 由于我们不知道countriesandcodes.txt 长什么样,所以很难给出一个好的答案。根据您发布的有关您的问题的内容...我同意@Gavin Perkins 的观点,看起来课程会派上用场。
  • 如果您的 countriesandcodes.txt 文件不是标准的、众所周知的格式(如 XML 或 JSON)?
  • @DanielMann 不是真正的原因。我只是在创建文件时添加了国家然后代码。我可以更改它以将创建文件的部分添加到我的问题中。我不再创建文件了,它只创建了一次。
  • @DanielDejunior 你能让文本文件用管道或逗号分隔吗? (例如:fr|france us|United States)
  • 我将文本文件更改为 csv 类型:Europe,eu Alps,alps Benelux,nl Germany,de Spain & Portugal,sp France,fr Greek,gr Italy,it Poland,pl Scandinavia,scan

标签: c# .net winforms


【解决方案1】:

这在技术上可能不是答案,但这里更好的方法是创建一个名为“Country”的类,并为其提供 url、国家名称等属性。然后你只需要创建一个列表(国家)和填充每个。

**给 Daniel d e Junior 的备注 (如果您可以提供 countryandcodes.txt 的外观,我将使用代码示例对其进行编辑)

【讨论】:

  • 我现在在问题底部添加了 countryandcodes.txt 的一部分,以便您了解它的格式。
  • 这在技术上和战略上都是正确的答案,上课会让这个问题更清楚。
【解决方案2】:

我想要的是在 imagesUrls 中创建列表,每个列表将首先包含国家名称列表中的国家名称,然后使用国家代码列表使用 imageUrlIrTrue 和 imageUrlIrFalse 的国家/地区链接

不确定“我想要的是在 imagesUrls 中创建列表”究竟是什么意思。

我的问题是你为什么要这样做?你真正需要做的是使用第一个编程,除了你需要考虑你需要什么类。

这是一个例子: 假设您有每个国家/地区的图片网址列表

class Country
{
  List<URL> URLList;
}

国家也有国家代码

class Country
{
  public List<URL> URLList{get;set;}
  public string Code {get;set;}
}

现在您可以抓取一个国家/地区并通过其网址循环播放。 尝试使用一些课程并修改您的问题,在更新时联系我,我将修改此答案以匹配问题。

【讨论】:

  • 我用我所做的尝试和我需要它做什么来更新我的问题。一般来说,我需要在 form1 中,我将能够使用循环来获取所有国家/地区的名称,所有国家/地区代码和每个国家/地区的链接。每个国家/地区应该有 18 个链接,因为每个链接在我构建它们时也是正确的和错误的。所以每个国家都有18个图片链接。
  • 例如,我将像这样在 form1 中创建一个循环: For(int i = 0; i
  • 例如,首先我只想遍历一个国家链接:土耳其。然后我想遍历其他国家,并在一个循环中获取这些国家的所有链接。
  • @DanielDejunior : 与其想你想做的事情,不如想想你的系统中有什么东西,每个“事物”都应该成为它自己的一个类,然后我们可以分解它并将其作为面向对象的编程练习。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
相关资源
最近更新 更多