c# - 查找两个列表中的差异

标签 c# algorithm list optimization comparison

我在想一个在两个列表中找出差异的好方法

问题是:

两个列表有一些字符串,其中前 3 个数字/字符(*分隔)表示唯一键(后跟文本 String="key1*key2*key3*text")。

这是字符串示例:

AA1*1D*4*The quick brown fox*****CC*3456321234543~

其中“*AA1*1D*4*”是唯一键

List1: "index1*index2*index3", "index2*index2*index3", "index3*index2*index3"

List2: "index2*index2*index3", "index1*index2*index3", "index3*index2*index3", "index4*index2*index3"

我需要匹配两个列表中的索引并进行比较。

  1. 如果 1 个列表中的所有 3 个索引都匹配另一个列表中的 3 个索引,我需要跟踪新列表中的两个字符串条目

  2. 如果一个列表中有一组索引没有出现在另一个列表中,我需要跟踪一侧并在另一侧保留一个空条目。 (上例中的#4)

返回列表

这是我到目前为止所做的,但我在这里有点挣扎:

        List<String> Base = baseListCopy.Except(resultListCopy, StringComparer.InvariantCultureIgnoreCase).ToList(); //Keep unique values(keep differences in lists)
        List<String> Result = resultListCopy.Except(baseListCopy, StringComparer.InvariantCultureIgnoreCase).ToList(); //Keep unique values (keep differences in lists)

        List<String[]> blocksComparison = new List<String[]>(); //we container for non-matching blocks; so we could output them later

        //if both reports have same amount of blocks
        if ((Result.Count > 0 || Base.Count > 0) && (Result.Count == Base.Count))
        {
            foreach (String S in Result)
            {
                String[] sArr = S.Split('*');
                foreach (String B in Base)
                {
                    String[] bArr = B.Split('*');

                    if (sArr[0].Equals(bArr[0]) && sArr[1].Equals(bArr[1]) && sArr[2].Equals(bArr[2]) && sArr[3].Equals(bArr[3]))
                    {
                        String[] NA = new String[2]; //keep results
                        NA[0] = B; //[0] for base
                        NA[1] = S; //[1] for result
                        blocksComparison.Add(NA);
                        break;
                    }
                }
            }
        }

你能为这个过程推荐一个好的算法吗?

谢谢

最佳答案

您可以使用 HashSet。

为 List1 创建一个 HashSet。请记住 index1*index2*index3 与 index3*index2*index1 不同。

现在遍历第二个列表。

Create Hashset for List1.

foreach(string in list2)
{
    if(hashset contains string)
       //Add it to the new list.
}

关于c# - 查找两个列表中的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9996151/

相关文章:

c# - TextBox:TextChanged 事件 - 输入 x 个字符时自动验证

c# - MultiBinding 转换器未绑定(bind)到 DataTemplate 中的 TextBlock

algorithm - 找到矩阵中最后一个像螺旋一样行走的正方形

python - Big O 符号是什么,用于按字母顺序对嵌套列表理解中的每个元素进行排序

c# - 数学舍入问题总计 > 100%

c# - 将我的 DTO 暴露给认为不正确的 View 吗?

c++ - 保持坐标排序

python - 在 Python 中对列表进行数字排序

regex - 匹配合法移动生成器

c# - 合并 k 个排序列表不适用于负值 C#