Click here to Skip to main content
15,899,126 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This below is the code to import the Text file in listbox1, and it works. I need the code that checks the content in listBox1...I mean excluding the lines that are already in the listbox1. Thank you.

C#
private void button1_Click(object sender, EventArgs e)
        {
          string sLine = "";
            using (StreamReader sr = new StreamReader(@"c:\Text.txt"))
            {
                while (!sr.EndOfStream)
                {
                    sLine = sr.ReadLine();
                    listBox1.Items.Add(sLine);
                    
                }
                
               MessageBox.Show("Completed..!");          

            }
        }    
Posted
Comments
Sergey Alexandrovich Kryukov 5-Jan-16 18:22pm    
First of all, what is "ListBox"? Which one? Full type name, please.
But in this case, it's probably not so important. What is your problem?
—SA

On of the possible solution is: couple ListBox with the instance of the class System.Collections.Generic.HashSet<>. You can even create a class derived from ListView. On each add or remove operation, make the content of the set in sync with the items.

Why? Because the time complexity of finding of an item is the set is O(1). Please see:
Big O notation - Wikipedia, the free encyclopedia[^],
Time complexity - Wikipedia, the free encyclopedia[^].

—SA
 
Share this answer
 
Comments
Member 10410972 6-Jan-16 3:55am    
I thought, that if exist any of the same items in Text.txt and listBox1, that such items can not be imported to the listBox1. Thank you.
Sergey Alexandrovich Kryukov 6-Jan-16 9:55am    
And..?
Did you actually understand my answer? I did not explain how to check up for existing item, thought it's obvious...
—SA
I found a solution. Thanks.
listBox1.Items.AddRange( File.ReadLines( @"C:\Text.txt" ).Distinct().Where( s => ! listBox1.Items.Contains( s )).ToArray() )
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900