简体   繁体   English

如何比较两个相同链接的列表?

[英]How can i compare two Lists for identical links?

Im calling this class from a timer tick event each X seconds: 我每隔X秒从计时器滴答事件中调用此类:

WebClient contents = new WebClient();
        List<string> links = new List<string>();
        public static List<string> FilteredLinks = new List<string>();
        List<string> Respones = new List<string>();
        public static List<List<string>> Threads = new List<List<string>>();

        public void Links(string FileName)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.Load(FileName);
            foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
            {
                HtmlAttribute att = link.Attributes["href"];
                if (att.Value.StartsWith("http://rotter.net/forum/scoops1"))
                {
                    links.Add(att.Value);
                }
            }

            for (int i = 0; i < links.Count; i++)
            {
                int f = links[i].IndexOf("#");
                string test = links[i].Substring(0, f);
                FilteredLinks.Add(test);
            }

links and FilteredLinks are both type List I need that it will check that if items already exist in the Lists don't add them again. 链接和FilteredLinks都是列表类型,我需要它检查列表中是否已经存在的项目不要再次添加。 Since its calling from a timer tick event so each X seconds the Lists are growing up with the same items over and over again. 因为它是从计时器滴答事件中调用的,所以每隔X秒,列表就会一次又一次地增长相同的项。

Use HashSet instead of List. 使用HashSet而不是List。 That way, you don't have to check for duplicate strings. 这样,您不必检查重复的字符串。

HashSet<string> links = new HashSet<string>();

A set is a collection that contains no duplicate elements, 集是不包含重复元素的集合,

http://msdn.microsoft.com/en-us/library/bb359438(v=vs.110).aspx http://msdn.microsoft.com/zh-CN/library/bb359438(v=vs.110).aspx

There are three ways to solve your problem 有三种方法可以解决您的问题

  1. Use the right data structure. 使用正确的数据结构。 HashSet as LB pointed out . HashSet如LB所指出

  2. Use Distinct to produce a list with only distinct after you done your adding 完成添加后,使用Distinct生成仅具有唯一性的列表

    links = link.Distinct();

  3. Use Contains before you call add 在调用添加之前使用包含


if (!links.Contains(att.Value))  
   links.Add(att.Value);

If case is an issue you'll need to pass in one the StringComparer s eg 如果遇到大小写问题,则需要传递一个StringComparer,例如

if (!links.Contains(att.Value, StringComparer.InvariantCultureIgnoreCase ))

You can make your own method for this 您可以为此制定自己的方法

             public boolean isPresent(List mylist,String search)
             {
             for(String str: myList) {
             if(str.trim().contains(search))
             return true;
             }
             return false;
              }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM