簡體   English   中英

如何檢查列表中是否已存在項目?

[英]How do i check if items already exist in the List?

for (int i = 0; i < t.Count; i++)
{
    if (!newText.Contains(t[i]))
    {
        if (firsttime > 1)
        {                           
                newText.Insert(0, string.Empty);
                newText.Insert(0, ExtractLinks.FilteredLinks[i]);
                newText.Insert(0, dateTimeList[i]);
                newText.Insert(0, t[i]);
        }
        else
        {
            newText.Add(t[i]);
            newText.Add(dateTimeList[i]);
            newText.Add(ExtractLinks.FilteredLinks[i]);
            newText.Add(string.Empty);
        }
    }
}

我通過計時器滴答聲事件多次調用此for循環。 變量t( List<string> )第一次包含43個項目。 List<string> newText包含172個項目。

我想檢查是否newText已經存在t任何項目,而不是再次將其添加到newText

我認為的問題是我正在遍歷t.Count ,我還應該以某種方式遍歷newText嗎? 我該如何解決,這樣情況才能正常工作?

如果使用的框架版本允許您使用System.Linq ,則可以使用Any()擴展名:

newText.Any(r => t.Contains(r));

如果在t也找到了newText一個成員,則擴展名將返回true。

編輯:事后,您可能可以使用.Except()擴展名更加優雅地進行此操作,但是我建議您在嘗試任何實際優化之前以一種簡單的方式進行操作。

編輯2:

    static void Main(string[] args)
    {
        var t = new List<string>();        // starts with 43 items
        var newText = new List<string>();  // starts with 172 items

        t.AddRange(Enumerable.Range(1, 43).Cast<string>());
        newText.AddRange(Enumerable.Range(1, 172).Cast<string>());

        // add only members t that do not exist in set newText (44..172 added)
        newText.AddRange(t.Except(newText));
    }

您可以添加項目並刪除所有重復的條目

yourList.Distinct().ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM