如何比较两个列表框的项目并将独特的项目复制到新的列表框

时间:2019-05-08 12:11:19

标签: c# listbox duplicates text-files

我有三个列表框。左边和中间的列表框有一些项目。我想比较左侧和中间列表框中的项目。我想将唯一项从中间列表框移到右侧列表框,我想要一个表达式句柄。

我尝试使用下面的代码来实现。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<string> FileNames = null;


    private void Btn_FileFolder_Click(object sender, EventArgs e)
    {
        using (FolderBrowserDialog FBDfolder = new FolderBrowserDialog())
        {

            if (FBDfolder.ShowDialog() == DialogResult.OK)
            {
                lbl_FolderPath.Text = FBDfolder.SelectedPath;
                FileNames = Directory.GetFiles(FBDfolder.SelectedPath).ToList();
                lstbx_filefolder.DataSource = FileNames.Select(f => Path.GetFileName(f)).ToList();
                lbl_NoOfFolderItems.Text = lstbx_filefolder.Items.Count.ToString();
            }
        }
    }

    private void Btn_TextFile_Click(object sender, EventArgs e)
    {
        OpenFileDialog textfile = new OpenFileDialog {
            Filter = "text (*.txt)|*.txt"
    };

        if (textfile.ShowDialog() == DialogResult.OK)
        {
            lbl_filepath.Text = textfile.FileName;

            string[] lines = File.ReadAllLines(lbl_filepath.Text);
            lstbx_textfile.Items.AddRange(lines);
            lbl_NoOfItems.Text = lstbx_textfile.Items.Count.ToString();

        }

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void btn_RemoveDuplicates_Click(object sender, EventArgs e)
    {
        var listboxfile = lstbx_filefolder.Items;
        var listboxtext = lstbx_textfile.Items;

        foreach (var itm in listboxfile)
        {
            if (listboxtext.Contains(itm)) listboxtext.Remove(itm); 
        }
    }

    private void btn_clear_Click(object sender, EventArgs e)
    {
        lstbx_filefolder.DataSource = null;
        //lstbx_filefolder.Items.Clear();
        lstbx_textfile.DataSource = null;
        lstbx_textfile.Items.Clear();

    }
}

}

enter image description here

1 个答案:

答案 0 :(得分:0)

在使用集合时,在许多情况下,您可以使用Linq来完成这些任务。

解决问题的第一步是将列表合并为一个列表 下一步是使用Linq从列表中获取唯一的字符串值,同时将Linq查询的结果分配给新的List。

通过使用Distinct()删除重复项。结果是这样的:

private void btn_RemoveDuplicates_Click(object sender, EventArgs e)
{
    var itemCollection = new List<string>();
    itemCollection.AddRange(lstbx_filefolder.Items);
    itemCollection.AddRange(lstbx_textfile.Items);


    var uniqueCollection = itemCollection.Distinct().ToList();

   // todo assign the values in the uniqueCollection to the source of the right listbox.
   `rightListBox`.Datasource = uniqueCollection; 
}