简体   繁体   English

删除类似的列表框项

[英]remove similar listbox items

I have a listbox with similar items, example: file1.exe=11, file1.exe=9 file2.exe=1, file3.zip=7, file7.zip=00, file3.zip=101 ...etc. 我有一个包含类似项目的列表框,例如:file1.exe = 11,file1.exe = 9 file2.exe = 1,file3.zip = 7,file7.zip = 00,file3.zip = 101 ...等等。 Now what I have to do is remove the similar items so i end up with: file1.exe=11, file3.zip=7, file3.zip=101 .. and so on. 现在,我要做的是删除类似的项,因此我最终得到:file1.exe = 11,file3.zip = 7,file3.zip = 101 ..等。 The numbers at the end are random, what matters is i don't get the same file name more than once. 末尾的数字是随机的,重要的是我没有多次获得相同的文件名。 Here is my lame attempt (overkill and does not work). 这是我la脚的尝试(矫kill过正,不起作用)。

    public void RemoveListboxDuplicates(ListBox ListBox)
    {
        List<String> filenames = new List<String>();
        List<String> unique = new List<String>(); 
        foreach (string itm in ListBox.Items)
        {
                string fname = itm.Substring(0, itm.LastIndexOf("="));
                filenames.Add(fname);
        }

        for (int i=0;i<filenames.Count;i++) 
        {
            if(!lstFiles.Items[i].ToString().Contains(filenames[i])) {
                unique.Add(lstFiles.Items[i].ToString());
            }
        }
        lstFiles.Items.Clear();

        foreach (string itm in unique)
        {
            lstFiles.Items.Add(itm);
        }
    }  

If the numbers after = do not matter, one way of doing it is this: 如果=之后的数字无关紧要,则一种处理方法是:

List<String> all = new List<String>();
foreach (string itm in ListBox.Items) {
    all.Add(itm);
}
var unique = all
    .GroupBy(s => s.Split('=')[0])
    .Select(g => g.First())
    .ToList();

The s.Split('=')[0] operation chops off the part after = , and uses the prefix as a grouping key. s.Split('=')[0]操作将=之后的部分切掉,并将前缀用作分组键。 Select(g => g.First()) part grabs the first element of each group, and ToList() makes the results into a List<string> again. Select(g => g.First())部分获取每个组的第一个元素,然后ToList()将结果再次放入List<string>

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

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